清除后为什么我的图像不重绘?

时间:2018-08-10 04:44:42

标签: javascript html5-canvas

清除后,我想重绘我的图像(现在它只是静态的,但将来会进行动画处理)。它只绘制一次,清除后却从不重新绘制图像,这是为什么呢?

var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');
var width = 640;
var height = 145;

var width2 = 640;
var height2 = 145;

startInterval();

function startInterval() {
  setInterval(function(){
    ctx.clearRect(0, 0, 640, 145);

    var text = new Image();
    var background = new Image();
    text.src = "../assets/img/title.svg";
    background.src = "../assets/img/mask.png";

    text.onload = function() {
      background.onload = function() {
        ctx.drawImage(text, 0, 0);
        ctx.globalCompositeOperation = 'source-in';
        ctx.drawImage(background, 0, 0, width, height);
        console.log("Drew image");
      };
    }
  }, 2000);
}

1 个答案:

答案 0 :(得分:0)

您的主要问题是,您永远不会重置上下文的globalCompositeOperation属性。

由于source-in将仅绘制位于现有非透明像素之上的新像素,因此,如果您的内容很清楚,则不会添加任何新像素。

要解决此问题,请在完成合成后将gCO设置为默认source-over


现在,我不能让您使用这样的代码...

不要嵌套这样的加载事件,因为它们都希望触发,所以很幸运,有了这个setInterval,否则在将处理程序附加到它之前,可能会触发背景的事件。

也不要像这样重置图像src

相反,只需加载一次资产,等待所有资产加载完毕,然后再启动例程/绘图。

var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');

var toLoad = 2; // how many assets are we waiting for
var assetsLoaded = 0; // a counter
var text = new Image();
var background = new Image();
// set the same handler for both Images
text.onload = background.onload = onassetload;
text.src = 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png';
background.src = 'https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg';

function onassetload() {
 assetsLoaded = assetsLoaded + 1; // udpate our counter
 if(assetsLoaded >= toLoad) { // all assets are ready
   startInterval();
 }
}
function startInterval() {
  c.width = text.width;
  c.height = text.height;
  setInterval(draw, 2000);
  draw();
function draw(){
    // here we just draw, no Image loading anymore
    ctx.clearRect(0, 0, c.width, c.height);
    ctx.drawImage(text, 0, 0);
    ctx.globalCompositeOperation = 'source-in';
    ctx.drawImage(background, 0, 0);
    // reset the gCO to its default
    ctx.globalCompositeOperation = 'source-over';
    console.log("Drew image");
  }
}
<canvas id="myCanvas"></canvas>