Search code examples
fabricjs

How can I resize an image in FabricJS?


I'm trying to resize an image which will then be exported and saved by the user. I've tried the following methods but neither of them are working for me.

The first method is to set the scaleX and scaleY. This does cause the image to be resized within the page, but doesn't seem to truly resize the image. In other words, it is being displayed at the proper size but the image data hasn't changed.

img.set({
    scaleX: newWidth/currentWidth,
    scaleY: newHeight/currentHeight
    });

The other method I tried was using the resize filter. Unfortunately, this doesn't appear to do anything. The other filters I'm using are working fine.

var canvas = new fabric.Canvas('c');
img.filters.push(new fabric.Image.filters.Resize({
    resizeType: 'hermite',
    scaleX: newWidth/currentWidth,
    scaleY: newHeight/currentHeight
}));
img.applyFilters();
canvas.requestRenderAll();

If anyone has any suggestions I'd appreciate it.


Solution

  • The problem was that I needed to obtain the resized image from image._element.toDataURL() rather than calling image.toDataURL().