繁体   English   中英

HTML5 Canvas将对象移动到鼠标单击位置

[英]HTML5 Canvas moving object to mouse click position

基本上我想将一个对象从A点(10x,10y)移动到画布上单击鼠标的位置(255x,34y)。

我目前正在使用一种方法,但它从++ X然后是++ Y到坐标; 然后是正确的。

我希望它直接进入位置,喜欢路径上的动画。 从A点到B点减速。

当你“移动”一个对象时,你真正需要做的就是擦除对象并重绘它

首先编写一个函数,它将在指定的x,y处重绘rect

function draw(x,y){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.beginPath();
    ctx.fillStyle="skyblue";
    ctx.strokeStyle="gray";
    ctx.rect(x,y,30,20);
    ctx.fill();
    ctx.stroke();
}

然后处理mousedown事件并调用draw函数

此示例使用jquery进行跨浏览器兼容,但您始终可以使用本机javascript进行重新编码。

// listen for all mousedown events on the canvas
$("#canvas").mousedown(function(e){handleMouseDown(e);});


// handle the mousedown event
function handleMouseDown(e){
  mouseX=parseInt(e.clientX-offsetX);
  mouseY=parseInt(e.clientY-offsetY);
  $("#downlog").html("Down: "+ mouseX + " / " + mouseY);

  // Put your mousedown stuff here
  draw(mouseX,mouseY);
}

这是代码和小提琴: http//jsfiddle.net/m1erickson/GHSG4/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;

    function draw(x,y){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        ctx.beginPath();
        ctx.fillStyle="skyblue";
        ctx.strokeStyle="gray";
        ctx.rect(x,y,30,20);
        ctx.fill();
        ctx.stroke();
    }

    function handleMouseDown(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      $("#downlog").html("Down: "+ mouseX + " / " + mouseY);

      // Put your mousedown stuff here
      draw(mouseX,mouseY);

    }

    $("#canvas").mousedown(function(e){handleMouseDown(e);});

    // start the rect at [10,10]
    draw(10,10);


}); // end $(function(){});
</script>

</head>

<body>
    <p>Click to redraw the rect at the mouse position</p>
    <p id="downlog">Down</p>
    <canvas id="canvas" width=300 height=300></canvas>

</body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM