gpt4 book ai didi

javascript - HTML canvas Javascript 鼠标事件,没有 jQuery

转载 作者:行者123 更新时间:2023-11-28 08:24:14 25 4
gpt4 key购买 nike

想知道是否可以使用鼠标事件(例如 mousedown)在 Canvas 上添加/删除圆圈。要点是能够移动 Canvas 上绘制的棋子。这里是我绘制碎片的代码,我添加了事件监听器,但我不知道如何绘制另一 block ,而是单击 Canvas 上的某个位置。

<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>

感谢您的帮助

最佳答案

您可以在 Canvas 上监听 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
}

这是一个演示: http://jsfiddle.net/m1erickson/tP3m4/

关于javascript - HTML canvas Javascript 鼠标事件,没有 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22617353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com