按住鼠标时,在画布上鼠标所在的位置连续绘制矩形



我正在尝试使用javascript和HTML画布制作一个绘图程序,我需要在鼠标的位置连续画一个圆圈,但我不确定如何做到这一点。我有一个大致的想法,但我的代码(毫不奇怪(不起作用。知道我该怎么做吗?代码在这里。

<canvas width = '450' height = '450' id = 'drawing'> </canvas>
<script>
var canvas = document.getElementById('drawing');
var ctx = canvas.getContext('2d')
var drawing = false
function startmoving(){ drawing = true;}
function stopmoving() { drawing = false;}
function draw() {
if (drawing == true){
ctx.fillstyle = 'black';
ctx.fillRect(event.clientX, event.clientY, 4, 4)
}
setInterval(drawing, 10);
}
</script>

您需要为画布设置一个mousedown/mouseup和mousemove监听器,然后如果鼠标向下,则在坐标处制作并放置一个矩形,如果鼠标向上,则停止绘制。此外,clientX和clientY用于页面的左上角可见部分。pageX和pageY用于页面的左上角。因此,如果你用clientX和clientY向下滚动,它会在当前页面的位置绘制,使其看起来很奇怪。修复?使用pageX和pageY(用pageX和pageY替换clientX和clientY(!

<!DOCTYPE html>
<html>
<body>
<canvas width='450' height='450' id='drawing'> </canvas>
<script>
var canvas = document.getElementById('drawing');
var drawing = false;
//start the drawing if the mouse is down
canvas.addEventListener('mousedown', () => {
drawing = true;
})
//stop the drawing if the mouse is up
canvas.addEventListener('mouseup', () => {
drawing = false;
});
//add an event listener to the canvas for when the user moves the mouse over it and the mouse is down
canvas.addEventListener('mousemove', (event) => {
var ctx = canvas.getContext('2d');
//if the drawing mode is true (if the mouse button is down)
if (drawing == true) {
//make a black rectangle
ctx.fillstyle = 'black';
//put the rectangle on the canvas at the coordinates of the mouse
ctx.fillRect(event.clientX, event.clientY, 4, 4)
}
});
</script>
</body>
</html>

最新更新