Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redraw canvas (every 250ms) without flickering between each redraw?

I wrote a function that draws out a slice of a pizza based on how big you specify it to be (in degrees)

function drawProgress(degs){

var canvas = document.getElementById('progress');
var context = canvas.getContext('2d');

context.globalAlpha=1;                
var img = new Image();
img.onload = function(){

    context.beginPath();
    context.arc(canvas.width/2,canvas.height/2, canvas.height/2, 0, degs * (-Math.PI/180), true);
    context.lineTo(canvas.width/2, canvas.height/2);
    context.clip();                        
    context.drawImage(img, 0, 0, canvas.width,canvas.width);
}                           
img.src = 'pizza.png';

}

When I try to call this function every 250ms, the progress is not updated after the first draw.

function runsEvery250ms(percent){
    drawProgress(3.6 * percent);
}

What changes do I need to make to the code to get the canvas to redraw each time drawProgress(degs) is called? Is it possible to perform redraws without causing the pizza to flicker?

like image 324
user784637 Avatar asked Mar 01 '12 19:03

user784637


1 Answers

Use context.clearRect(0, 0, canvas.width, canvas.height); and cache your image, don't reload each time you refresh

UPDATE: No idea if this will work, untested and been a while since I used canvas but try it

var canvas = document.getElementById('progress');
var context = canvas.getContext('2d');
var img = new Image();
var imgLoaded = false;
img.src = 'pizza.png';

img.onload = function(){
  imgLoaded = true;
}

function drawProgress(degs){
    context.save();
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.globalAlpha=1;                

    context.beginPath();
    context.arc(canvas.width/2,canvas.height/2, canvas.height/2, 0, degs * (-Math.PI/180), true);
    context.lineTo(canvas.width/2, canvas.height/2);
    context.clip();                        
    if (imgLoaded) context.drawImage(img, 0, 0, canvas.width,canvas.width);
    context.restore();
}
like image 155
TimCodes.NET Avatar answered Nov 10 '22 01:11

TimCodes.NET