如何将globalCompositeOperation与三个图像一起使用?

时间:2015-11-01 09:26:56

标签: javascript html html5 canvas html5-canvas

如何使用此功能在蓝色和绿色之间放置一个蓝色框?

我需要达到这个效果。

enter image description here

这是Codepen

HTML

<canvas id="canvas">
</canvas>

JS

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');

window.onload = draw;

green = new Image;
green.src = 'http://www.thebouncingbox.com/images/thumbnail/produkte/large/California-Sunbounce-meterware-green-box.jpg';

red = new Image;
red.src = 'http://www.front-porch-ideas-and-more.com/image-files/color-red.jpg';

blue = new Image;
blue.src = 'http://s3.amazonaws.com/colorcombos-images/colors/000066.png';

function draw() {
 ctx.drawImage(green, 0, 0, 200, 200);
 ctx.drawImage(red, 80, 50, 120, 100);
  ctx.drawImage(blue, 60, 30, 100, 100);
}

2 个答案:

答案 0 :(得分:2)

  

在绘制图像之前,您需要先监听图像的onload事件。要将图像放在图像上,系列操作会有所帮助!

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
window.onload = draw1;

function draw1() {
  var green = new Image();
  green.onload = function() {
    ctx.drawImage(green, 0, 0, 200, 200);
    draw2();
  };
  green.src = 'http://www.thebouncingbox.com/images/thumbnail/produkte/large/California-Sunbounce-meterware-green-box.jpg';
}

function draw2() {
  var blue = new Image;
  blue.onload = function() {
    ctx.drawImage(blue, 50, 50, 100, 100);
    draw3();
  };
  blue.src = 'http://s3.amazonaws.com/colorcombos-images/colors/000066.png';

}

function draw3() {
  var red = new Image();
  red.onload = function() {
    ctx.drawImage(red, 100, 100, 100, 100);
  };
  red.src = 'http://www.front-porch-ideas-and-more.com/image-files/color-red.jpg';
}
<canvas id="canvas" width="200" height="200"></canvas>

答案 1 :(得分:1)

为什么不改变你画的顺序?

function draw() {
ctx.drawImage(green, 0, 0, 200, 200);
ctx.drawImage(blue, 60, 30, 100, 100);   
ctx.drawImage(red, 80, 50, 120, 100);
}