Alex Nikolsky
Alex Nikolsky

Reputation: 2179

How to use globalCompositeOperation with three images?

How can I place a blue box between red and green one using this function?

I need to achieve this effect.

enter image description here

Here's a 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);
}

Upvotes: 2

Views: 290

Answers (2)

lucas
lucas

Reputation: 1505

Why not change the order you draw them?

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

Upvotes: 1

Rayon
Rayon

Reputation: 36609

You need to listen onload event of the image before drawing it. To have images over image, series operation will help!

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>

Upvotes: 2

Related Questions