Created
January 21, 2022 14:06
-
-
Save codeonion/39a34641ed6a6e2ce542248d1646424d to your computer and use it in GitHub Desktop.
Canvas Draw Quick
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- html blank page --> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Document</title> | |
</head> | |
<body> | |
<!-- canvas --> | |
<canvas id="canvas" width="500" height="500"></canvas> | |
<!-- clear button --> | |
<button id="clear">Clear</button> | |
</body> | |
<!-- jquery --> | |
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> | |
<script> | |
// Draw on canvas with mouse | |
var canvas = document.getElementById("canvas"); | |
var ctx = canvas.getContext("2d"); | |
var lastX = -1; | |
var lastY = -1; | |
$("#canvas").mousedown(function () { | |
console.log("mousedown"); | |
$(this).mousemove(function (e) { | |
var mouseX = e.pageX - this.offsetLeft; | |
var mouseY = e.pageY - this.offsetTop; | |
if (lastX > -1) { | |
// render a point | |
ctx.beginPath(); | |
ctx.moveTo(lastX, lastY); | |
ctx.lineTo(mouseX, mouseY); | |
ctx.strokeStyle = "black"; | |
ctx.lineWidth = 5; | |
ctx.stroke(); | |
ctx.closePath(); | |
} | |
lastX = mouseX; | |
lastY = mouseY; | |
}); | |
}).mouseup(function () { | |
$(this).unbind('mousemove'); | |
}).mouseout(function () { | |
$(this).unbind('mousemove'); | |
}); | |
// canvas.addEventListener("mousedown", function(e){ | |
// this.addEventListener("mousemove", function (e) { | |
// var mouseX = e.pageX - this.offsetLeft; | |
// var mouseY = e.pageY - this.offsetTop; | |
// if (lastX > -1) { | |
// ctx.beginPath(); | |
// ctx.moveTo(lastX, lastY); | |
// ctx.lineTo(mouseX, mouseY); | |
// ctx.strokeStyle = "black"; | |
// ctx.lineWidth = 5; | |
// ctx.stroke(); | |
// ctx.closePath(); | |
// } | |
// lastX = mouseX; | |
// lastY = mouseY; | |
// }); | |
// }).mouseup(function () { | |
// $(this).unbind('mousemove'); | |
// }).mouseout(function () { | |
// $(this).unbind('mousemove'); | |
// }); | |
// Clear canvas | |
var clearCanvas = document.getElementById("clear"); | |
clearCanvas.addEventListener("click", function () { | |
ctx.clearRect(0, 0, canvas.width, canvas.height); | |
lastX = -1; | |
lastY = -1; | |
}); | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment