【问题标题】:How to redraw canvas (every 250ms) without flickering between each redraw?如何重绘画布(每 250 毫秒)而不在每次重绘之间闪烁?
【发布时间】:2012-03-01 19:06:01
【问题描述】:

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

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) 时,我需要对代码进行哪些更改才能使画布重绘?是否可以在不导致披萨闪烁的情况下执行重绘?

【问题讨论】:

  • 好久没碰canvas了,我想你需要在每帧重绘后清空canvas。
  • 清除画布而不使其闪烁的代码是什么?
  • 每次重绘时不要重新加载图像
  • @LedZeppelin 查看 Chimoo 的 clearRect 语法以清除画布的答案。

标签: javascript html canvas html5-canvas


【解决方案1】:

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

【讨论】:

  • 我在哪里添加这行代码?我把它放在context.globalAlpha=1; 之前,它在第一次加载后进度卡住了?另外,你能给我一些关于如何“缓存”图像的代码(即我需要在我的函数中进行哪些更改)?非常感谢,谢谢!
猜你喜欢
  • 2013-08-27
  • 1970-01-01
  • 2015-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-05
相关资源
最近更新 更多