我需要从屏幕左上角到屏幕右下角制作一张图片的动画。我只能使用javascript。我做了一些研究,但每个人都使用 CSS 或 Jquery 来制作动画,所以我找不到问题的答案。所以我的问题是如何确定屏幕的右下角以及如何将图片精确地动画到那个点? 我试过了,但这只是穿过屏幕进入无穷大。 这是我的代码:
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';
}
最佳答案
我在这里做了一个简单的例子:
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);
就像 SeanOlson 所说的那样,无论高度如何,要让它到达特定的 Angular 落,您都必须决定如何增加顶部和左侧的位置。您可以使用时间戳和 requestAnimationFrame 来保持流畅,没有抖动。
这里有一个关于 requestAnimationFrame 的不错的教程:http://creativejs.com/resources/requestanimationframe/
**第二次编辑 我忘了提,以防你不知道 rAF 在旧浏览器中不可用。不过,Paul Irish 有一个 polyfill:
http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
关于javascript - 仅使用 javascript 在屏幕上显示图像动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30404562/