0

我在画布上有一个五边形图形,我想将其移动到鼠标所在的位置。

代码

<canvas id="fld" width="1000px" height="800"></canvas>
    <script type="text/javascript"><!--
    onload = function() { draw(); };
    function draw() {
      var canvas = document.getElementById('fld');
      if ( ! canvas || ! canvas.getContext ) {return false;}
      var ctx = canvas.getContext('2d');
      //Pentagon
      ctx.beginPath();
      ctx.strokeStyle = 'rgb(255, 0, 0)';
      ctx.moveTo(100,10);
      for (var i=1;i<=5; ++i) {
        th=i * 2 * Math.PI/5;
        x=100+90*Math.sin(th);
        y=100-90*Math.cos(th);
        ctx.lineTo(x,y);
      }
      ctx.stroke();
      ctx.beginPath();
      ctx.arc(900, 60, 40, 0, 2 * Math.PI, false);
      ctx.fillStyle = "rgb(255, 0, 0)";
      ctx.fill();
      ctx.strokeStyle = "black";
      ctx.stroke();
     }
    </script>
4

1 回答 1

1

您只需要进行一些更改,这将起作用。

首先,您应该更改您的 draw() 函数,使其接受 2 个参数,即图形将要绘制的 X 和 Y 位置。接下来,您需要更改您使用的硬编码值,以便它们基于传递的 X 和 Y 值。

其次,您应该向画布添加一个 onclick 处理程序。当您收到点击事件时,您可以获得鼠标被点击的画布的 X 和 Y 坐标。

然后,您可以清除画布并通过鼠标单击 X 和 Y 调用更新的绘图函数。

Look-up onclick handlers for the way to get the position of the mouse when the button is pressed. You'll have to use addEventListener to attach the click handler, so that your function gets the event that triggered it passed to it. You can then extract the co-ords of the click from the event object.

于 2013-02-22T13:39:24.233 回答