Reputation: 33
I need to animate a picture from the top left of the screen to the bottom right of the screen. I can only use javascript. I made some research but everyone using CSS or Jquery for animation so I couldn't find answer for my question. So my questions are how can I determine the bottom right of the screen and how can I animate the picture exactly to that point? I tried this but this just goes across the screen into infinity. Here is my code:
var imgObj = null;
var animate;
function init(){
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
imgObj.style.top = '0px';
}
function moveRight(){
imgObj.style.left = parseInt(imgObj.style.left) + 1 + 'px';
animate = setTimeout(moveRight,60); // call moveRight in 60msec
imgObj.style.top = parseInt(imgObj.style.top) + 1 + 'px';
}
Upvotes: 1
Views: 1445
Reputation: 2885
I made a simple example here:
http://plnkr.co/edit/xnuBO5RRrjjnMJZjkxEu
(function(window){
var imgLeft = 0, imgTop = 0;
var imgObj, screenWidth, screenHeight, finalTop, finalLeft,
slope, imgHeight, imgWidth;
var animateImage = function(){
imgObj.style.left = imgLeft < finalLeft ? imgLeft + 'px' : finalLeft + 'px';
imgObj.style.top = imgTop < finalTop ? imgTop + 'px' : finalTop + 'px';
if(imgLeft !== finalLeft || imgTop !== finalTop){
requestAnimationFrame(animateImage);
}
imgLeft++;
imgTop += slope;
};
window.onload = function(){
imgObj = document.getElementById('image');
screenWidth = window.innerWidth;
screenHeight = window.innerHeight;
imgHeight = imgObj.offsetHeight;
imgWidth = imgObj.offsetWidth;
slope = (screenHeight - imgHeight) / (screenWidth - imgWidth);
finalTop = screenHeight - imgHeight;
finalLeft = screenWidth - imgWidth;
requestAnimationFrame(animateImage);
};
})(window);
Like SeanOlson said, to get it to go to the specific corner no matter what the height you are going to have to decide how to increment your top and left positions. You can use time stamps and requestAnimationFrame to keep things smooth with no jutter.
There is a decent tutorial on requestAnimationFrame here: http://creativejs.com/resources/requestanimationframe/
**Second Edit I forgot to mention, in case you aren't aware rAF isn't available in older browsers. Paul Irish has a polyfill for it though:
http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
Upvotes: 1
Reputation: 379
"How can I determine the bottom right of the screen and how can I animate the picture exactly to that point?"
You get the dimensions of the display through the window object:
var width = window.innerWidth;
var height = window.innerHeight;
Because you're positioning the picture by it's upper-left corner, the final position will be
var final_top = height - img_height;
var final_left = width - img_width;
Then you use a simple loop or perhaps a interval timer to move the image incrementally until it reaches those coordinates.
Upvotes: 1