How to move an image to another place on the screen. The user picks the location by clicking the mouse somewhere within the window.
This builds on the last code base, which featured the mouse Position finder code.
Watch It In Action (View source to get the code)
A couple of notes to keep in mind:
- You can only click once, then you have to wait for it to get to it's destination
- log() - Puts a message in the div, a cheap debugging technique
- move() - The meat! What we call a re-cursive function, is called again and again until the object reaches its destination
- findPos() - returns the position of an object, this is actual a cheater function as it does not get the true position of an object. (see mobLib for the full function)
var speed = 1;
var moving = false;
pos = getMousePos(e); //from included js file
moving = true;
log("Clicked: " + pos + "," + pos);
log("Object is in the process of moving.");
log("Click refresh to start over.");
document.getElementById("log").innerHTML = msg + "
" + document.getElementById("log").innerHTML;
function move(objID, destX, destY)
var obj = document.getElementById(objID);
var pos = findPos(objID);
currentX = pos;
currentY = pos;
newX = currentX;
newY = currentY;
if(destX > currentX)
//log("X:" + destX + " vs CurrentX: " + currentX);
if(destX <> currentY)
if(destY < top =" newY;" left =" newX;" t =" setTimeout(" moving =" false;" posx =" 0;" posy =" 0;" e =" window.event;" posx =" e.pageX;" posy =" e.pageY;" posx =" e.clientX" posy =" e.clientY" out =" new" obj =" document.getElementById(objectID);" curleft =" curtop" curleft =" obj.offsetLeft" curtop =" obj.offsetTop" onclick =" mouseClicked;">
Some things to try and play with:
- Can you speed up the movement to the destination?
- Can you add more images and allow the user to control more than 1?
- Can you make the image move so that it's center ends up on the destination point? (right now the top left corner ends up there)