我编写了一个使用 HTML5 画布的非常简单的 JavaScript。当用户在画布上单击鼠标时,脚本会获取他们的鼠标坐标,然后当他们按住鼠标移动鼠标时,它会绘制一条线,重复此过程直到他们松开鼠标。但它不起作用,我不知道为什么?在此先感谢您的帮助。
<body>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #000000;">
</canvas>
<script>
// Canvas link
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// Variables
var x1;
var y2;
var isPressed = false;
// Event listeners
context.addEventListener('mousedown', functionMouseDown, false);
context.addEventListener('mousemove', functionMouseMove, false);
context.addEventListener('mouseup', functionMouseUp, false);
function functionMouseDown() {
// Get coordinates
x1 = mousePos.x;
y1 = mousePos.y;
isPressed = true;
}
function functionMouseMove() {
// If mouse is down and moved start drawing line
if (isPressed == true) {
drawLine();
}
}
function functionMouseUp() {
// Stop drawing line
isPressed = false;
}
function drawLine() {
// Draw line
context.moveTo(x1,y1);
context.lineTo(x,y);
context.stroke();
// Set start coordinates to current coordinates
x1 = x;
y1 = y;
}
</script>
</body>
</html>