0

I am using Fabric.js and jQuery UI for a drag and drop scene creator. When I drag and drop an image into the canvas the image becomes blurry/pixelated and appears to be zoomed in. I've been searching Stackoverflow and Google forever and can't find any solutions. I'd appreciate any suggestions on how to fix it!

Here is my code:

// HTML

<canvas id="scene"></canvas>

// Draggable setup

$('.scene-item').draggable({
    helper: 'clone',
    appendTo: 'body',
    containment: 'window',
    scroll: false,
    zIndex: 9999
});

// Drop Setup

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

canvas.setDimensions({
    width: '800px',
    height: '500px'
}, {
    cssOnly: true
});
document.getElementById("scene").fabric = canvas;

canvas.on({
    'object:moving': function(e) {
        e.target.opacity = 0.5;
    },
    "object:modified": function(e) {
        e.target.opacity = 1;
    }
});


$('#scene').droppable({
    drop: function(e, ui) {
        if ($(e.target).attr('id') === 'scene') {
            var pointer = canvas.getPointer();
            fabric.Image.fromURL(ui.draggable[0].currentSrc, function (img) {
                console.log(img);
                img.set({
                    left: pointer.x - 20,
                    top: pointer.y - 20,
                    width: 52,
                    height: 52,
                    scale: 0.1
                });
                //canvas.clear();
                canvas.add(img);
                canvas.renderAll();
            });
        }
    }

});

This is what the images look like on and off the canvas:

enter image description here

Here is a demo jsfiddle.net/dmLr6cgx/1

Dhiraj
  • 33,140
  • 10
  • 61
  • 78
Ryan
  • 122
  • 1
  • 13

1 Answers1

4

I figured out the problem. I had to replace:

canvas.setDimensions({
        width: '800px',
        height: '500px'
    }, {
        cssOnly: true
    });

with

canvas.setHeight(500);
canvas.setWidth(800);
canvas.renderAll();

And now it works fine.

Ryan
  • 122
  • 1
  • 13
  • Wow this is legit a solution. I was giving height and width via constructor but this saved my day. In the newest version it's requestRenderAll btw. – Axl Mar 07 '18 at 14:52
  • Yo, could y'all check this out and tell me why it might be doing this? https://stackoverflow.com/questions/62457067/fabric-js-bad-image-quality?noredirect=1#comment110504735_62457067 – Shmack Jul 29 '20 at 00:19