我的 Canvas 动画在 Chrome 中像冰一样流畅,但在 Firefox 中却像糟糕的发型一样不稳定。最奇怪的是,这甚至不是一个复杂的计算。有谁发现我的代码有任何问题(与性能相关),可能导致速度下降?
这是 jsfiddle 上的: http://jsfiddle.net/Wu5Jh/
这是为SO:
$(document).ready(function(){
//vars
var x = 20,
y = 20,
pi = Math.PI,
width,
height,
complete = 100,
refreshInterval,
ctx;
// computed vars
function init() {
ctx = $('#canvas')[0].getContext("2d");
width = $("#canvas").width();
height = $("#canvas").height();
center = [width/2, height/2];
refreshInterval = (function doSetTimeout(){
draw();
setTimeout(doSetTimeout, 30);
})();
};
function circle(x,y,r) {
// Draw the growing circle
ctx.fillStyle = "#09f";
ctx.beginPath();
ctx.moveTo(x, y); // center of the pie
ctx.arc(
x,
y,
r,
-2*pi*complete/100 + pi*1.5,
-pi*.5,
true
);
ctx.lineTo(x, y);
ctx.closePath();
ctx.fill();
// Draw the cutout
ctx.globalCompositeOperation = "xor";
ctx.fillStyle = "#fff";
ctx.beginPath();
ctx.arc(x,y,r/2,0,pi*2,true);
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, width, height);
}
function timeCheck(){
if (complete>0){
complete -= 1;
}
else {
clearInterval(refreshInterval);
}
}
function draw() {
clear();
circle(x, y, 20);
timeCheck();
}
init();
});
我希望避免使用 Flash 动画或 gif,但我可能别无选择。
谢谢!
最佳答案
我确实没有看到任何问题,并且我在 Linux 上使用 Chromium 8 和 Firefox 3.6.13。
但是,如果您仍然需要微观优化的建议,那么您可以制作诸如 -2*pi/100
、1.5*pi
和 之类的内容。 5*pi
作为自己的常量。另外,这只是一个猜测,但使用 "copy"
而不是 "xor"
进行 ctx.globalCompositeOperation
可能会更快。您还可以存储为绘制的第一条弧计算的弧 Angular ,并将其用于第二条弧,而不仅仅是让它绘制一个完整的圆。
关于javascript - Canvas 中的动画不连贯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4446960/