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

标签 javascript html canvas

想知道是否可以使用鼠标事件(例如 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/

相关文章:

javascript - 如何使用 Bootstrap-Tour 和动态路径处理多页面游览?

javascript - 文档中的 CKEditor 样式表

html - 带标题的 CSS 砌体网格?

html - 是否可以在悬停叠加层上设置文本

javascript - Canvas 上的鼠标悬停事件

javascript - 将 Canvas 的一部分复制到图像

JavaScript:在 Canvas 中旋转对象

javascript - 尝试将 promise 的 Angular 动态数组发送到表达服务器

javascript - URL 参数看起来像目录

javascript - Scraper 不使用 Cheerio 使用 jquery 返回任何值