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.
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With