Answer the question
In order to leave comments, you need to log in
How to overlap one image with another in canvas?
For example, in the following example, I want the green box to be on top of the red one.
How to achieve this?
My Codepen
HTML
<canvas id="canvas">
</canvas>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
window.onload = draw;
img1 = new Image;
img1.src = 'http://www.thebouncingbox.com/images/thumbnail/produkte/large/California-Sunbounce-meterware-green-box.jpg';
img2 = new Image;
img2.src = 'http://www.front-porch-ideas-and-more.com/image-files/color-red.jpg';
function draw() {
ctx.drawImage(img1, 0, 0, 200, 200);
ctx.drawImage(img2, 100, 0, 200, 200);
}
Answer the question
In order to leave comments, you need to log in
Each next drawing is overlaid on top of what you already have on the canvas, so just paint in reverse order.
ctx.drawImage(img2, 100, 0, 200, 200);//Сначала красный
ctx.drawImage(img1, 0, 0, 200, 200);//А далее поверх него зеленый
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question