gpt4 book ai didi

javascript - 我使用 Raphael 的动画滞后,为什么?

转载 作者:行者123 更新时间:2023-11-28 21:01:12 24 4
gpt4 key购买 nike

我已经设置了 demo illustrating animation on a circle shape ,并且渲染时圆圈似乎摇摇欲坠。是什么导致动画滞后?怎样才能让它顺利呢?

我尝试将 setInterval() 的使用替换为对 animate() 的调用,如注释代码中所示,但无济于事。

var WINDOW_HEIGHT = 400;
var WINDOW_WIDTH = 600;

var paper = Raphael(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);

Circle = function(paper, x, y, r, color) {
this.paper = paper;
this.x = x;
this.y = y;
this.r = r;
this.color = color;
this.xd = 1;
this.yd = 1;
this.elem;
}

Circle.prototype.create = function() {
this.elem = this.paper.circle(this.x, this.y, this.r);
this.elem.attr("fill", this.color);
this.elem.attr("stroke", this.color);
}

Circle.prototype.move = function() {

if (this.x < 0 || this.x > WINDOW_WIDTH) {
this.xd = -this.xd;
}
if (this.y < 0 || this.y > WINDOW_HEIGHT) {
this.yd = -this.yd;
}
this.x += this.xd;
this.y += this.yd;

this.elem.attr("cx", this.x);
this.elem.attr("cy", this.y);
}

Circle.prototype.animate = function(x, y) {
this.elem.animate({
cx: x,
cy: y
}, 1000, "linear");
}

var circle = new Circle(paper, 0, 0, 30, "#f00");

circle.create();

window.setInterval(function() {
circle.move();
}, 1);

//circle.animate(300, 300);​​

最佳答案

这是间隔为 1 毫秒的 setInterval 的副作用。浏览器无法真正处理这个问题。相反,根据时间计算位置,并且仅在最后一帧完成时请求新帧:

var _requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function(f) { setTimeout(f, 16); };

var lastUpdate = new Date().getTime();

var update = function() {
// How many milliseconds has it been since the last update?
var now = new Date().getTime();
var d = now - lastUpdate;
lastUpdate = now;

// Now, move the ball based on the difference.
// Looping is not the right way to go about this, mind.
var amountBallMoved = d / 33;

for(var i = 0; i < amountBallMoved; i++)
circle.move();

// And finally, request the next animation frame.
_requestAnimationFrame(update);
};

update();​​​

Here's an updated jsFiddle.

关于javascript - 我使用 Raphael 的动画滞后,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11015804/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com