我在画布上有一个五边形图,我想将它移动到鼠标所在的位置。
CODE
<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>
答案 0 :(得分:1)
您只需进行一些更改即可。
首先,您应该更改draw()函数,使其占用2个参数,即绘制图形的X和Y位置。接下来,您需要更改所使用的硬编码值,以便它们基于传递的X和Y值。
其次,您应该在画布上添加一个onclick处理程序。当您收到点击事件时,您可以获得单击鼠标的画布的X和Y坐标。
然后,您可以清除画布并使用鼠标单击X和Y调用更新的绘图功能。
查找onclick处理程序,了解按下按钮时获取鼠标位置的方法。您必须使用addEventListener来附加单击处理程序,以便您的函数获取触发它传递给它的事件。然后,您可以从事件对象中提取点击的合作数据。