Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fabricjs. How to insert image with rounded borders?

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...

like image 831
user2455079 Avatar asked Mar 10 '23 15:03

user2455079


1 Answers

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/

like image 63
janusz Avatar answered Mar 13 '23 04:03

janusz