Very Very new to Javascript, just trying to learn :)
What I want to do is have an image (will ultimately be a sprite) at default location, then when I click the right mouse button on the screen, I want the image to gradually move to that location?
I did some research but couldn't find this specifically.
Ultimately I want to have a animated game character that I can move on the screen using the right mouse button.
Like everyone else said stay away from right click, heres an example using jQuery.
Live Demo
var $follower = $("#follower"),
mouseX = 0,
mouseY = 0;
$(document).click(function(e){
mouseX = e.pageX;
mouseY = e.pageY;
$follower.stop().animate({left : mouseX, top: mouseY});
});
and pure JS updated 2017 to use requestAnimationFrame
instead of setTimeout
Demo
var mouseX = 0,
mouseY = 0,
follower = document.getElementById("follower"),
xp = 0,
yp = 0;
document.onclick = function(e){
mouseX = e.pageX;
mouseY = e.pageY;
};
function animate(){
requestAnimationFrame(animate);
xp += (mouseX - xp) / 12;
yp += (mouseY - yp) / 12;
follower.style.left = xp + 'px';
follower.style.top= yp + 'px';
}
animate();
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