Reputation: 117
I need to create a new image cropped to the transparent area of the PNG.
I understand I can use the clipTo(path) function to create the new image.
However, my problem is creating the path in the first place. How can I create a path from the transparent area of a PNG?
Thanks in advance.
Upvotes: 1
Views: 809
Reputation: 136638
As strange as it may seem, I wasn't able to find a correct duplicate for this...
You don't need to calculate a path from your bitmap. CanvasRenderingContext2d API offers some compositing and blending options, which will allow you to work directly with bitmaps.
fabricjs also offers this option: http://fabricjs.com/docs/fabric.Object.html#globalCompositeOperation
var c = new fabric.Canvas('c', {
imageSmoothingEnabled: false
});
fabric.Image.fromURL(
'https://dl.dropboxusercontent.com/s/4e90e48s5vtmfbd/aaa.png',
function(image1) {
fabric.Image.fromURL(
'https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg',
function(image2) { // the one to be clipped
c.add(image1);
c.add(image2);
c.renderAll();
}, {
globalCompositeOperation: 'source-in', // will be drawn only where pixels are already drawn
top: -300,
left: -400
});
}, {
width: 200,
height: 200
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.18/fabric.js"></script>
<canvas id="c" width="500" height="500"></canvas>
Upvotes: 3