Overlay visible areas of transparent black silhouette PNG with pattern using CSS3 or JS

不羁岁月 提交于 2019-12-12 02:46:28

问题


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.


回答1:


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);


来源:https://stackoverflow.com/questions/23587669/overlay-visible-areas-of-transparent-black-silhouette-png-with-pattern-using-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!