Updating a small script to work with the latest version of Fabric.JS (2.4.1)
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I have this small script and I've tried updating it to work with Fabric.JS 2.4.1 but can't seem to get it working. I'd like someone to please make the changes required to have it work with this new v. of Fabric.JS. Here is a JSFiddle that I'm playing with:

http://jsfiddle.net/code4ever/kgbzd1ny/

As you'll see, adding images distorts them.

Please let me know if I can provide more info that'll lead to a solution. Thank you!

awarded to Wuddrum

Crowdsource coding tasks.

3 Solutions


In img.set, the options width and height are used to set the size to be cropped from the uploaded image.
To initially set the size of the image, use the scaleToWidth and scaleToHeight options.


m8928 is right with the scaling instead of using the width and height in the .set() block, here is the actual code block for the createImage() function with the width,height properties removed and the scaling methods inserted

function createImage (dataUrl) {
    fabric.Image.fromURL(dataUrl, function (img) {
        var withBorder = document.querySelector('.initial-border').classList.contains('active')
        var oImg = img.set({
        left: 40,
        top: 40,
        angle: 00, //<--remove width and height
        stroke: '#07C', //<-- set this
        strokeWidth: withBorder ? 5 : 0 //<-- set this
    }).scale(0.9);
    oImg.scaleToWidth(100); //<--add ScaletoWidth and Height
    oImg.scaleToHeight(100);
    canvas.add(oImg).renderAll();
    var a = canvas.setActiveObject(oImg);
    var dataURL = canvas.toDataURL({
        format: 'png',
        quality: 0.8
    });
    });
}
Winning solution

Here's my solution: JSFiddle

I've also fixed the issue with image borders resizing along with the image, this also works when resizing multiple images.

On top of that I've added the ability to toggle the border for multiple selected images (previously it would only work if a single image was selected).

Very neat, thanks!
sharper 28 days ago
View Timeline