Asked  8 Months ago    Answers:  5   Viewed   34 times

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

 Answers

87

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.

Wednesday, March 31, 2021
 
jenny
answered 8 Months ago
84

It is possible to listen for events on the inner object by adding the option: subTargetCheck: true to the fabric.Group object.

    // create a group
    let group = new fabric.Group([circle, rect], {
        subTargetCheck: true
    });

    circle.on('mousedown', function(e) { 
        // e.target should be the circle
        console.log(e.target);
    });
Sunday, August 22, 2021
 
IanB
answered 2 Months ago
48
var dataURL = canvas.toDataURL({
  format: 'png',
  multiplier: 4
});

Use multiplier property in toDataURL().

Friday, August 27, 2021
 
vivek
answered 2 Months ago
17

Use NUM_FRACTION_DIGITS

fabric.Object.NUM_FRACTION_DIGITS = 10;

value = number of digit you want after decimal.

The default value is 2.

Monday, August 30, 2021
 
David542
answered 2 Months ago
47

Fabric objects have the following methods for centering:

obj.center();  // Centers object vertically and horizontally on canvas to which is was added last
obj.centerV(); // Centers object vertically on canvas to which it was added last
obj.centerH(); // Centers object horizontally on canvas to which it was added last

I don't see anything about offset in the docs.

Something like the following would probably work

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

$(window).resize(function(){

     var w = $(window).width();
     var h = $(window).height();
     var center = {x:w / 2, y:h / 2);

     canvas.setDimensions({width:w,height:h});
     canvas.forEachObject(function(obj){

        obj.set({
            left : center.x + obj.offsetLeft,
            top : center.y + + obj.offsetTop,
        });

        obj.setCoords();

    });

// need to call calcOffset whenever the canvas resizes
canvas.calcOffset();
canvas.renderAll();

});
Wednesday, September 15, 2021
 
user3009344
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :