如何重绘画布(每250ms),每次重绘之间没有闪烁?

时间:2012-03-01 19:06:02

标签: javascript html5 canvas html5-canvas

我写了一个函数,根据你指定它的大小(以度为单位)绘制出一片披萨

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';

}

当我尝试每隔250毫秒调用此函数时,第一次绘制后进度不会更新。

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

每次调用drawProgress(degs)时,我需要对代码进行哪些更改以使画布重绘?是否可以在不使比萨饼闪烁的情况下进行重绘?

1 个答案:

答案 0 :(得分:14)

使用context.clearRect(0, 0, canvas.width, canvas.height);并缓存图片,每次刷新时都不要重新加载

更新:不知道这是否可行,未经测试并且已经有一段时间了,因为我使用了画布但是尝试了

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();
}