Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

javascript - Fabric.js how to clip by image

The title say it all. You can see Fabric.js Mask Filter Demo. This should be pretty simple but I can't find any example of applying mask to Fabric.js.

I am trying to apply mask to my JSFiddle. http://jsfiddle.net/ZxYCP/342/

From my JSFiddle, my goal is to have both logo and pugImg clipped inside this picture (or any picture if you want). Well, I can't even mask one picture anyway, so if this is not bothering you, please update the JSFiddle for better explanation.

In addition, the code from @kangax, creator of Fabric.js <3, in this question should be the solution but I can't manage to work. The result should be like the image below. Any further suggestion is appreciated.

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are not really trying ot mask an image. You are using some compositing effects. There are a couple of things to understand that are not directly related to fabric.js.

A mask goes over an image.

The demo link you posted will not make you get the effect as in the screenshot.

If this is the case, you should have:

  • a light blue canvas

  • a pug.jpg image

  • a white overlay image with a girl-shaped transparent hole in it

Make a sandwich with those 3. In this case you are masking the canvas not the image.

If you have a girl-shaped path, you can clip the canvas as seen in:

Fabric.js Clip Canvas (or object group) To Polygon

But you state that you want to use a image instead. So if you do not have the overlay with girl-shaped hole, you can use another solution to get the same effect:

  • a transparent canvas

  • a light blu image with a shape you need and transparent pixels all around

  • a pug.jpg image

Add the first image on the canvas; set the globalCompositeOperation of the pug.jpg to 'source-atop' paint the other image over the other

var canvas = new fabric.Canvas('c');

fabric.Image.fromURL('http://fabricjs.com/assets/2.svg', function(img){
  img1 = img;
  fabric.Image.fromURL('http://fabricjs.com/assets/pug.jpg', function(img){
    img1.scaleToWidth(canvas.getWidth());
    img2 = img;
    img2.scaleToHeight(300);
    img2.left = 50;
    img2.top = 50;
    img2.globalCompositeOperation = 'source-atop';
    canvas.add(img1);
    canvas.add(img2);
  });
});
<script type ="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<canvas id="c" width="400" height="400" style="border:1px solid #ccc"></canvas>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...