javascript 画布四处走动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13880785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:02:16  来源:igfitidea点击:

Canvas moving circle around

javascripthtmlcanvas

提问by user1514042

Could anyone post a simple solution for moving a circle by mouse using HTML5 canvas? I've made a readup on various frameworks (easel, fabrics, paper etc) - while they're all pretty cool I only need a small circle to follow the mouse pointer, which isn't worth 100K+ of code.

任何人都可以发布一个使用 HTML5 画布通过鼠标移动圆圈的简单解决方案吗?我已经阅读了各种框架(画架、织物、纸张等)——虽然它们都很酷,但我只需要一个小圆圈来跟随鼠标指针,这不值得 100K+ 的代码。

回答by Loktar

Live Demo

现场演示

I probably shouldn't just give it away without you having tried anything. Anyway here you go hope it helps.

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

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;
});

?

?