JSFiddle - React, Tailwind, and code Playground
by m1erickson
HTML
<h4>Second grass image is drawn only where<br>house pixels already existed<br>(Uses 'source-in' compositing)</h4>
<canvas id="canvas" width=300 height=300></canvas>
<p>Original images</p>
<img src='https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house100x100.png'><img src='https://dl.dropboxusercontent.com/u/139992952/stackoverflow/mower_start.png'>
CSS
body{ background-color: ivory; }
canvas{border:1px solid red;}
JavaScript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// put the paths to your images in imageURLs[]
var imageURLs = [];
// push all your image urls!
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house100x100.png");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/mower_start.png");
// the loaded images will be placed in images[]
var imgs = [];
var imagesOK = 0;
loadAllImages(start);
function loadAllImages(callback) {
for (var i = 0; i < imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function () {
imagesOK++;
if (imagesOK >= imageURLs.length) {
callback();
}
};
img.onerror = function () {
alert("image load failed");
}
img.crossOrigin = "anonymous";
img.src = imageURLs[i];
}
}
function start() {
// the imgs[] array now holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
ctx.drawImage(imgs[0], 50, 50);
ctx.globalCompositeOperation = 'source-in';
ctx.drawImage(imgs[1], 0, 0);
}