Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas moving circle around [closed]

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.

like image 907
user1514042 Avatar asked Dec 26 '22 13:12

user1514042


1 Answers

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

like image 179
Loktar Avatar answered Jan 05 '23 09:01

Loktar