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

I wrote a function that draws a slice of pizza based on how big you specify it (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 250 ms, 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 in order to redraw the canvas each time when drawProgress(degs) ? Is it possible to redraw without causing the pizza to flicker?

+7
source share
1 answer

Use context.clearRect(0, 0, canvas.width, canvas.height); and cache your image, do not reboot every time you update

UPDATE: I don’t know if this will work, it’s unverified and some time has passed since I used the canvas, but I will 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(); } 
+14
source

All Articles