Javascript:带有参数的函数会导致动画滞后
Javascript: function with parameters cause lag in animation
首先:我试图搜索一个类似的问题,但除了在标题中如何描述外,我真的不知道如何描述它。因此,如果某个地方已经有了解决方案,请告诉我。
我试图理解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>
由于我忙于学习这些东西,我很好奇我能为此做出什么改进。
您正在运行一个无限循环。你必须给出一个停止动画的条件。在我的代码中,它只是一个示例。
尝试:
<div id="box1" style="position: absolute">x</div>
<button onclick="init();">Test</button>
<script type="text/javascript">
var xInit, yInit;
function init() {
b = document.getElementById("box1");
xInit = 0;
yInit = 0;
moveIt(b, xInit, 850, yInit, 450);
}
function moveIt(theobject, x, endx, y, endy) {
x += Math.floor((endx - xInit)*0.01);
y += Math.floor((endy - yInit)*0.01);
theobject.style.left = x + "px";
theobject.style.top = y + "px";
if ( x < endx )
requestAnimationFrame(function() {moveIt(theobject, x, endx, y, endy)});
}
</script>
相关文章:
- 如何设置html元素填充的动画
- 如何使用动画实现纸张推车
- Javascript:为什么我的Raphaeljs动画滞后?它'It’s甚至不一致
- 选择2.js和jQuery幻灯片动画滞后/抖动
- 始终运行的 Web 应用程序上的动画滞后和性能问题
- Javascript:悬停时滞后;制作幻灯片动画
- Javascript:带有参数的函数会导致动画滞后
- 淡入淡出背景颜色更改动画会滞后并减慢速度
- "滞后“;魔兽世界动画网站
- HTML动画,无滞后
- 如何使Vanilla Javascript动画不那么滞后
- scrollTop动画在chrome中是滞后的,但在firefox中工作得很好(背景尺寸:封面问题?)
- HTML5/JavaScript游戏在制作动画时的严重滞后
- SVG动画在调整大小后非常滞后(专家)
- JavaScript动画在几个循环后滞后
- jQuery动画意外滞后
- 画布外 - 左侧导航栏动画在关闭时非常跳跃/滞后
- 为什么我的jQuery SlideDown动画滞后/跳跃
- 动画图像数组滞后
- 动画:jQuery VS CSS:jQuery滞后,为什么?-jsFiddle比较/示例