1 回答

TA貢獻1998條經(jīng)驗 獲得超6個贊
您需要為畫布設置一個 mousedown/mouseup 和 mousemove 監(jiān)聽器,然后在鼠標按下時在坐標處創(chuàng)建并放置一個矩形,如果鼠標抬起則停止繪制。另外,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>
添加回答
舉報