这是我第一次来这里,我不知道如何缩进这个抱歉:/
我有一张面包车的图片,我正试图将它移过屏幕,让它看起来就像在开车一样。 完成后,我将缩放图像,使其看起来好像在移动(并变小)。
我需要在没有任何包(例如 JQuery)的情况下使用标准 javascript 完成此操作。
我得到的是一辆货车,由于我无法抛 anchor 的原因,它沿着两条路径而不是一条路径行驶。同样朝错误的方向移动(它应该沿着路径 y=-25x 移动,这样每向右移动 25 个像素它应该向上移动 1 个像素)。
为了说明我想要实现的目标,请看这张图片: http://i.stack.imgur.com/9WIfr.jpg
这是我的 javascript 文件:
var viewWidth = 800;
var viewHeight = 480;
var fps = 30;
var delay = getFrame(fps);
var vanWidth, vanHeight, vanObj;
function initVan() {
vanObj = document.getElementById("van");
vanObj.style.position = "absolute";
vanObj.src = "pics/delivery/van.png";
vanWidth = 413;
vanHeight = 241;
var startX = 0-vanWidth;
var startY = viewHeight-vanHeight;
setPosition(startX,startY);
transition(startX,startY,3000);
}
function transition(startX,startY,time) {
//the intention of this is to follow a path y=-25x in mathematical terms
var endX = viewWidth;
var endY = startY-(endX/-25);
//note that this is the velocity per millisecond
var velocityX = (endX-startX)/time;
var velocityY = (endY-startY)/time;
alert(endY+", "+startY);
move(velocityX,velocityY,endX,endY);
}
function move(vX,vY,eX,eY) {
var posX = getX();
var posY = getY();
if (posX<=eX || posY<=eY) {
//velocityX (in milliseconds) * delay = the amount of pixels moved in one frame @fps=30
var moveX = vX*delay;
var moveY = vY*delay;
var newX = posX+moveX;
var newY = posY+moveY;
setPosition(newX,newY);
setTimeout(function() {
move(vX,vY,eX,eY);
}, delay);
}
}
function getX() {
return vanObj.offsetLeft;
}
function getY() {
return vanObj.offsetTop;
}
function setPosition(newX,newY) {
vanObj.style.left = newY + "px";
vanObj.style.top = newX + "px";
}
function setSize(scaleX,scaleY) {
vanWidth *= scaleX;
vanHeight *= scaleY;
vanObj.width = vanWidth;
vanObj.height = vanHeight;
}
function getFrame(fps) {
return Math.floor(1000/fps);
}
这是我的 HTML 文件:
<script type="text/javascript" src="delivery.js"> </script><br/>
<body onLoad="initVan();"><br/>
<img id="van" width=413 height=241/>
最佳答案
除非您不需要库,或者特别喜欢重新发明轮子,否则我会使用 jQuery 的效果库来解决这个问题,尤其是 .animate:http://api.jquery.com/animate/ .请参阅该页面上的第一个示例。
$(document).ready(function() {
$('#van')
.attr({
width: 413,
height: 241 //etc.
})
.animate({
width: "70%",
height: "70%" //etc.
}, 3000);
});
更少的代码意味着更少的维护。意味着满意的客户。
关于javascript - 使用 JavaScript 将图像从 A 移动到 B,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8021779/