画布移动圈子

时间:2012-12-14 14:39:45

标签: javascript html5 canvas

有人会发布一个简单的解决方案,使用HTML5画布通过鼠标移动圆圈吗?我已经对各种框架(画架,布料,纸张等)进行了读取 - 虽然它们都非常酷我只需要一个小圆圈来跟随鼠标指针,这不值得100K +代码。

1 个答案:

答案 0 :(得分:9)

<强> Live Demo

我可能不应该在没有尝试任何事情的情况下放弃它。无论如何,你希望它有所帮助。

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

canvas.width = canvas.height = 500;

var targetX = 0,
    targetY = 0,
    x = 10,
    y = 10,
    velX = 0,
    velY = 0,
    speed = 2;

function update(){
    var tx = targetX - x,
        ty = targetY - y,
        dist = Math.sqrt(tx*tx+ty*ty),
        rad = Math.atan2(ty,tx),
        angle = rad/Math.PI * 180;

        velX = (tx/dist)*speed,
        velY = (ty/dist)*speed;

        x += velX
        y += velY

        ctx.clearRect(0,0,500,500);
        ctx.beginPath();
        ctx.arc(x,y,5,0,Math.PI*2);
        ctx.fill();

    setTimeout(update,10);
}

update();

canvas.addEventListener("mousemove", function(e){
    targetX = e.pageX;
    targetY = e.pageY;
});