Search code examples
fabricjs

Fabric JS move image inside the image container


I need a functionality where i need to be able to position image properly inside the frame of the image itself.

enter image description here

As you can see in the image, the image container will be of a fixed size, and if the image is bigger than the frame itself, I need to be able to reposition image inside the frame. I tried clipping the image with a rectangle and positioning the image inside the rectangle but the clip creates a new image equal to the size of the rectangle so it has not worked so far. Is there any property in the fabric.Image class that lets us move image position inside?


Solution

  • Since Fabric.js v2, image cropping can be done using a combination of four properties: width, height, cropX, and cropY. (http://fabricjs.com/v2-breaking-changes#image)

    As an example, an image with native dimensions of 500x500 pixels can be center cropped to 300x300 pixels like this:

    img.set({
      width: 300,
      height: 300,
      cropX: 100,
      cropY: 100
    });