移动对象以使用画布单击甚至X和Y.

时间:2016-10-12 22:20:45

标签: javascript html5 canvas html5-canvas

我想知道是否可以将画布上的形状从另一组坐标移动到画布上的特定坐标。在这种情况下,是否可以获取鼠标单击的位置并创建一个在特定时间内移动到该点的对象?感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var x2=100,y2=100;
var dx=0,dy=0;
var counter=10;

canvas.width = canvas.height = 256;
var shape = {x:100, y:100, width : 50, height : 30};

function clear() {
  ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
  ctx.fillRect(0,0,canvas.width,canvas.height);
}

function draw(){
if(counter>0){
    shape.x=shape.x+dx;
    shape.y=shape.y+dy;
    ctx.clearRect(0,0,256,256);
    ctx.fillStyle = "red";
    ctx.strokeStyle = "black";
        ctx.fillRect(shape.x, shape.y, shape.width, shape.height);
        ctx.strokeRect(shape.x, shape.y, shape.width,shape.height);
    counter--;
    setTimeout(draw,20)
    }
}

canvas.addEventListener("click", function(e) {
    clear();
    x2=e.clientX;
    y2=e.clientY;

    dx=(x2-shape.x)/10;
    dy=(y2-shape.y)/10;
    counter=10;
    draw();
});

draw();

</script>