Hong Yi
Hong Yi

Reputation: 74

Fabric.js 1.5 image clipto

I'm using Fabric.js to draw an image on canvas and then draw a rectangle when clicking down and moving mouse.

I want to crop the image using the rectangle.

When invoking the clipTo() function, I found Fabric.js doesn't clip the image from the specified position. It seems x:0, y:0 actually indicates the central point of the image instead of top left corner of the image.

If I use the code below, I'll only get bottom right part of the image.

object.clipTo = function (ctx) {
    ctx.rect(0, 0, 700, 700);
};

Does anyone know how to calculate the correct start point (x, y)?

Upvotes: 1

Views: 1097

Answers (1)

AndreaBogazzi
AndreaBogazzi

Reputation: 14731

This happen because when clipping the current transform is positioned on center of object.

To avoid this, change your clipTo function as follow:

object.clipTo = function (ctx) {
     ctx.save();
     ctx.setTransform(1,0,0,1,0,0);
     ctx.rect(0, 0, 700, 700);
     ctx.restore();
};

Basically you reset with setTransform the position of canvas to "neutral" And with save and restore you bring it back where fabricjs expects it to be,

in this way you will clip exactly from 0,0 to 700,700.

UPDATE MARCH 2017

If you are working with screen that have a devicepixelRatio bigger than 1 ( retina screens, mobile devices ) you may need different code:

object.clipTo = function (ctx) {
     var retina = fabric.getRetinaScaling();
     ctx.save();
     ctx.setTransform(retina,0,0,retina,0,0);
     ctx.rect(0, 0, 700, 700);
     ctx.restore();
};

Upvotes: 1

Related Questions