【发布时间】:2014-12-31 05:26:15
【问题描述】:
首先:我尝试搜索类似的问题,但除了我在标题中的做法之外,我真的不知道如何描述这个问题。因此,如果某处已经有解决方案,请告诉我。
我正在尝试了解 OOP 在 javascript 中的工作原理。我有一些操作脚本的经验。为了练习,我写了这段代码。当页面加载时,它使一个框从左向右移动。现在我想重写代码,如果我想创建多个动画框,我不需要数百个函数来处理同一种动画。
这是我的旧代码,有效:
<script>
var dx = 850;
var x = 0;
var y = 450;
function init() {
b = document.getElementById("box1");
moveIt();
}
window.requestAnimFrame = (function() {
return window.requestAnimationFrame OR
window.webkitRequestAnimationFrame OR
window.mozRequestAnimationFrame OR
window.oRequestAnimationFrame OR
window.msRequestAnimationFrame OR
function (/* function */ callback, /* DOMElement */ element)
{
window.setTimeout(callback, 1000 / 60);
};
})();
function moveIt() {
x += (dx - x) * 0.15;
b.style.left = x + "px";
b.style.top = y + "px";
requestAnimFrame(moveIt, b);
}
</script>
</head>
<body onload="init()">
<div style="width:50px;height:50px;background:blue;position:absolute;" id="box1"></div>
</body>
这是第二个版本,我尝试让动画的功能更加动态。它似乎确实有效,但似乎滞后,或者它根本不做动画,我不确定,因为它很难检查。
<script>
function init() {
b = document.getElementById("box1");
moveIt(b, 0, 850, 0, 450);
}
window.requestAnimFrame = (function() {
return window.requestAnimationFrame OR
window.webkitRequestAnimationFrame OR
window.mozRequestAnimationFrame OR
window.oRequestAnimationFrame OR
window.msRequestAnimationFrame OR
function (/* function */ callback, /* DOMElement */ element)
{
window.setTimeout(callback, 1000 / 60);
};
})();
function moveIt(theobject, x, endx, y, endy) {
x += (endx - x) * 0.15;
y += (endy - y) * 0.15;
theobject.style.left = x + "px";
theobject.style.top = y + "px";
requestAnimFrame(moveIt(theobject, x, endx, y, endy), b);
}
</script>
</head>
<body onload="init()">
<div style="width:50px;height:50px;background:blue;position:absolute;" id="box1"></div>
</body>
由于我正忙于学习这些东西,我很好奇我可以为此做出的任何改进。
【问题讨论】:
标签: javascript function animation parameters lag