Last Good Quote: Son's are the seasoning on our lives. - Someone on Facebook

Monday, November 24

Javascript - Move that Image

Another Code Report,

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)
I purposely did not comment well, if you need to have comments for these simple functions, you may want to get something a bit easier to work with. (my 2 cents)

var speed = 1;
var moving = false;
function mouseClicked(e)
pos = getMousePos(e); //from included js file
moving = true;
move("player", pos[0],pos[1]);
log("Clicked: " + pos[0] + "," + pos[1]);
log("Object is in the process of moving.");
log("Click refresh to start over.");

function log(msg)
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[0];
currentY = pos[1];
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)


MrMaxx said...

Perhaps you should use something like this =>

Post a Comment