Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving an image to the position of the mouse?

Tags:

javascript

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 image 858
lross1309 Avatar asked Sep 19 '11 19:09

lross1309


1 Answers

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();
like image 147
Loktar Avatar answered Oct 04 '22 14:10

Loktar