想知道是否可以在画布上添加/删除带有鼠标事件的圆圈,例如mousedown。能够移动画布上绘制的棋子的主要观点。在这里我的代码绘制了各个部分,我添加了事件监听器,但我不知道如何绘制另一个部分,而是单击画布上的某个位置。
<script type="text/javascript">
var canvas=document.getElementById("checkerboard");
var context2d=canvas.getContext("2d");
canvas.addEventListener("mousedown", moveP, false);
function play(){
context2d.fillStyle="red";
for(var x=0; x<8; x++){
for(var y=0; y<3; y++){
if(((x+y)%2)==1){
context2d.beginPath();
context2d.moveTo(x*80+5, y*80+40);
context2d.arc(x*80+40, y*80+40, 30, 0, 2*Math.PI);
context2d.lineWidth=15;
context2d.strokeStyle="#9F000F";
context2d.stroke();
context2d.fill();
}
}
}
context2d.fillStyle="grey";
for(var x=0; x<8; x++){
for(var y=5; y<8; y++){
if(((x+y)%2)==1){
context2d.beginPath();
context2d.moveTo(x*80+5, y*80+40);
context2d.arc(x*80+40, y*80+40, 30, 0, 2*Math.PI);
context2d.lineWidth=15;
context2d.strokeStyle="#B6B6B4";
context2d.stroke();
context2d.fill();
}
}
}
}
</script>
感谢您的帮助
答案 0 :(得分:0)
你可以在画布上监听mousedown和mouseup事件,如下所示:
// get references to the canvas and its context
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// get the bounding box of the canvas
// (needed when calculating the mouse position)
var BB=canvas.getBoundingClientRect();
var offsetX=BB.left;
var offsetY=BB.top;
// tell the browser to trigger handleMousedown & handleMouseup
// in response to mouse events
canvas.onmousedown=handleMousedown;
canvas.onmouseup=handleMouseup;
你可以回复这样的鼠标事件:
function handleMousedown(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// calculate the mouse position
var mouseX=e.clientX-offsetX;
var mouseY=e.clientY-offsetY;
//now do your mouse down stuff
}
function handleMouseup(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// calculate the mouse position
var mouseX=e.clientX-offsetX;
var mouseY=e.clientY-offsetY;
//now do your mouse up stuff
}