Choppy animations in canvas
My canvas animation is smooth as ice in chrome, but choppy as a bad haircut in firefox. The strangest thing is, it's not even a complex calculation. Does anyone see anything wrong (performance related) with my code that could cause this slowdown?
Here it is on jsfiddle: http://jsfiddle.net/Wu5Jh/
And here it is for 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开发者_JAVA百科, width, height);
}
function timeCheck(){
if (complete>0){
complete -= 1;
}
else {
clearInterval(refreshInterval);
}
}
function draw() {
clear();
circle(x, y, 20);
timeCheck();
}
init();
});
I was hoping to avoid a flash animation or gif, but I might have no choice.
Thanks!
I don't really see any problems and I am using Chromium 8 and Firefox 3.6.13 on Linux.
However, if you still want suggestions for micro optimizations, then you can make things like -2*pi/100
, 1.5*pi
, and .5*pi
as their own constants. Also, this is just a guess, but using "copy"
instead of "xor"
for ctx.globalCompositeOperation
might be faster. You could also store the arc angle that is computed for the first arc drawn and use it for the second as well rather than just having it draw a full circle.
精彩评论