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

我正在尝试使用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>


慕容708150
浏览 80回答 1
1回答

米琪卡哇伊

您需要为画布设置一个 mousedown/mouseup 和 mousemove 监听器,然后在鼠标按下时在坐标处创建并放置一个矩形,如果鼠标抬起则停止绘制。另外,clientX 和 clientY 用于页面左上角的可见部分。pageX 和 pageY 位于页面的左上角。因此,如果你使用 clientX 和 clientY 向下滚动,它将绘制在当前页面的位置,使其看起来很奇怪。修复?使用 pageX 和 pageY(将 clientX 和 clientY 替换为 pageX 和 pageY)!<!DOCTYPE html><html><body>&nbsp; <canvas width='450' height='450' id='drawing'> </canvas>&nbsp; <script>&nbsp; &nbsp; var canvas = document.getElementById('drawing');&nbsp; &nbsp; var drawing = false;&nbsp; &nbsp; //start the drawing if the mouse is down&nbsp; &nbsp; canvas.addEventListener('mousedown', () => {&nbsp; &nbsp; &nbsp; drawing = true;&nbsp; &nbsp; })&nbsp; &nbsp; //stop the drawing if the mouse is up&nbsp; &nbsp; canvas.addEventListener('mouseup', () => {&nbsp; &nbsp; &nbsp; drawing = false;&nbsp; &nbsp; });&nbsp; &nbsp; //add an event listener to the canvas for when the user moves the mouse over it and the mouse is down&nbsp; &nbsp; canvas.addEventListener('mousemove', (event) => {&nbsp; &nbsp; &nbsp; var ctx = canvas.getContext('2d');&nbsp; &nbsp; &nbsp; //if the drawing mode is true (if the mouse button is down)&nbsp; &nbsp; &nbsp; if (drawing == true) {&nbsp; &nbsp; &nbsp; &nbsp; //make a black rectangle&nbsp; &nbsp; &nbsp; &nbsp; ctx.fillstyle = 'black';&nbsp; &nbsp; &nbsp; &nbsp; //put the rectangle on the canvas at the coordinates of the mouse&nbsp; &nbsp; &nbsp; &nbsp; ctx.fillRect(event.clientX, event.clientY, 4, 4)&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; </script></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript