7

I have a canvas drawn in Fabric.js that i am adding a group of rectangles to, i want to limit the edges of those rectangles as a group to not go outside a certain area.

Imagine making a stripy t-shirt, the stripes are make by using a series of rectangles and i need to keep them to the shape of the t-shirt.

I think its better to clip the entire canvas to the shape of the t shirt, so anything i add to it remains within the t-shirt but i am stuck. So far i am only clip to basic circles and rectangles.

Thanks

fiscme
  • 422
  • 1
  • 6
  • 20

2 Answers2

23

You can just render a shape inside canvas.clipTo :)

I just loaded a random SVG shape in kitchensink and did this:

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

canvas clipped to a shape

As you can see, entire canvas is now clipped by that SVG shape.

Vito Gentile
  • 13,336
  • 9
  • 61
  • 96
kangax
  • 38,898
  • 13
  • 99
  • 135
0

You may also try this one: http://jsfiddle.net/ZxYCP/198/

enter image description here

var clipPoly = new fabric.Polygon([
    { x: 180, y: 10 },
    { x: 300, y: 50 },
    { x: 300, y: 180 },
    { x: 180, y: 220 }
], {
    originX: 'left',
    originY: 'top',
    left: 180,
    top: 10,
    width: 200,
    height: 200,
    fill: '#DDD', /* use transparent for no fill */
    strokeWidth: 0,
    selectable: false
});

You can simply use Polygon to clip. Answer is based on @natchiketa idea in this question Multiple clipping areas on Fabric.js canvas

Community
  • 1
  • 1
l00k
  • 1,525
  • 1
  • 19
  • 29