Question

I'm looking for a way to overlay the visible areas of a transparent black silhouette PNG file with a certain pattern.

Is there a CSS, JavaScript, mixed solution for this?

Example: I have one image of a weapon silhoutte and a set of camo patterns which I want to lay over the weapon.

Demo: In Photoshop the same result is givin when selecting layer mask > overlay.

Ps: my question is similar to this thread: Silhouette a PNG image using CSS except I am looking for the exact opposite.

Was it helpful?

Solution

You can do this using canvas with globalCompositeOperation set to destination-in. For example

var canvas = document.createElement('canvas');
canvas.width = 250;
canvas.height = 250;

var canvas_context = canvas.getContext("2d");

var img = new Image();
img.onload = function(){
    var msk = new Image();
    msk.onload = function(){
        canvas_context.drawImage(img, 0, 0);
        canvas_context.globalCompositeOperation = "destination-in";
        canvas_context.drawImage(msk, 0, 0);
        canvas_context.globalCompositeOperation = "source-over";
    };

    msk.src = 'silhouette.png';
}
img.src = 'pattern.jpg';

document.body.appendChild(canvas);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top