0

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.

Community
  • 1
  • 1
mdbxz
  • 189
  • 2
  • 11

1 Answers1

3

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);
NoGray
  • 1,149
  • 7
  • 9
  • Thanks a heap NoGray. That code was exactly what I was looking for. Result here: http://jsfiddle.net/eLmmA/1/ [1]: http://i.stack.imgur.com/QtQrZ.png [2]: http://i.stack.imgur.com/MDGFY.jpg – mdbxz May 11 '14 at 09:20