4

Need to insert image to fabric js and make rounded borders to it. (NOT to whole canvas) Read answer here:

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

But i can't reproduce clipping as that guy made.

var clip = canvas.item(0);
var obj = canvas.item(1);
canvas.remove(clip);
obj.clipTo = function(ctx) {
  clip.render(ctx);
};

Tried to make svg rectange and clip image to it: http://jsfiddle.net/ZxYCP/657/

I'm getting unexpected behavior...

Community
  • 1
  • 1
user2455079
  • 420
  • 4
  • 16

1 Answers1

9

Here is an example how it can be done:

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

function roundedCorners(ctx) {
  var rect = new fabric.Rect({
    left:0,
    top:0,
    rx:20 / this.scaleX,
    ry:20 / this.scaleY,
    width:this.width,
    height:this.height,
    fill:'#000000'
  });
  rect._render(ctx, false);
}

fabric.Image.fromURL('http://fabricjs.com/lib/pug.jpg', function(img) {
  img.set({
    angle: 45,
    width: 500,
    height: 500,
    left: 140,
    top: 100,
    scaleX: 0.3,
    scaleY: 0.3,
    clipTo: roundedCorners.bind(img)
  });
  canvas.add(img).setActiveObject(img);
});

See fiddle here: http://jsfiddle.net/ZxYCP/659/

janusz
  • 828
  • 6
  • 9
  • But this will clip whole canvas instead of needed object, so that's not a solution... – user2455079 Nov 25 '16 at 07:29
  • Ahh, sorry, your question wasn't clear to me. Check out the updated answer, there is one way to get it done. You can change your rounded corners radius using `rx` and `ry` properties. In this example I divided `rx` and `ry` by the image scale to keep the radius absolute regardless the image scale but you want it relative just set to whatever value you need. Hopefully it helps. – janusz Nov 25 '16 at 09:46
  • 1
    But this is clipping stroke as well if set to image :( – kalpeshdeo May 16 '17 at 13:28