1 回答
TA贡献1998条经验 获得超6个赞
您需要为画布设置一个 mousedown/mouseup 和 mousemove 监听器,然后在鼠标按下时在坐标处创建并放置一个矩形,如果鼠标抬起则停止绘制。另外,clientX 和 clientY 用于页面左上角的可见部分。pageX 和 pageY 位于页面的左上角。因此,如果你使用 clientX 和 clientY 向下滚动,它将绘制在当前页面的位置,使其看起来很奇怪。修复?使用 pageX 和 pageY(将 clientX 和 clientY 替换为 pageX 和 pageY)!
<!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>
添加回答
举报