首页 文章

HTML canvas Javascript鼠标事件,没有jQuery

提问于
浏览
1

我想知道是否可以在画布上添加/删除带有鼠标事件的圆圈,例如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>

谢谢你的帮助

1 回答

  • 0

    You can listen for mousedown and mouseup events on the canvas like this:

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

    And you can respond to mouse events like this:

    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
    }
    

    Here's a Demo: http://jsfiddle.net/m1erickson/tP3m4/

相关问题