简体   繁体   中英

Fabric.js: clip everything but overlay image

My code on js fiddle: http://jsfiddle.net/tbqrn/170/

var img02URL = 'http://fabricjs.com/lib/pug.jpg';

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

//frame image, should be displayed fully.
canvas.setOverlayImage('http://cdn.1001freedownloads.com/vector/thumb/107559/Pink_Hearts_Frame.png',           canvas.renderAll.bind(canvas), {
        width: canvas.width,
        height: canvas.height 
    });
canvas.selection = false;

//rectangle that hides everithing around it.
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.rect(50,50,300,300);
ctx.closePath();
ctx.stroke();
ctx.clip();

//the image that should stay inside the frame
fabric.Image.fromURL(img02URL, function(oImg) {
    oImg.scale(.25);
    oImg.left = 140;
    oImg.top = 140;
    canvas.add(oImg);
    canvas.renderAll();
});

In my current approach everything around rectangle is hidden even overlay image. I want to hide everything but overlay image, so the frame is displayed fully. How can I do that?

Just let fabricJs manage the clipping for you. The overlay image is above clipping in fabricjs rendering stack.

When using fabricjs do not access directly the context, but access it with fabricjs methods. Use canvas.clipTo = function(_2dContext){} to manage your clipping.

 var img02URL = 'http://fabricjs.com/lib/pug.jpg'; var canvas = new fabric.Canvas('canvas'); //frame image, should be displayed fully. canvas.setOverlayImage('http://cdn.1001freedownloads.com/vector/thumb/107559/Pink_Hearts_Frame.png', canvas.renderAll.bind(canvas), { width: canvas.width, height: canvas.height }); canvas.selection = false; //rectangle that hides everithing around it. canvas.clipTo = function(ctx) { ctx.rect(50,50,300,300); ctx.closePath(); }; //the image that should stay inside the frame fabric.Image.fromURL(img02URL, function(oImg) { oImg.scale(.25); oImg.left = 140; oImg.top = 140; canvas.add(oImg); canvas.renderAll(); }); 
 <script src="http://www.deltalink.it/andreab/fabric/fabric.js" ></script> <canvas id="canvas" width=400 height=400 style="height:500px;width:500px;"></canvas> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM