Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fabric.js background appears only after click

With the following code I create a Fabric canvas

canvas = new fabric.Canvas('canvas');
canvas.setWidth(660);
canvas.setHeight(590);

fabric.Image.fromURL('assets/img/materials/marble.bmp', function(image) {
    image.set({
        // I need this because the image size and the canvas size could be different
        // in this way the image always covers the canvas
        width:660,
        height:590
    });

    canvas.setBackgroundImage(image);
});

canvas.renderAll();

The canvas is created, but the background image doesn't appear unless I click inside the canvas, as I click inside the canvas the background appears.

I'm working on my local machine and the application will not be published online.

Why do you think that I'm having this problem? Am I doing anything wrong? How could I fix this behaviour?

like image 497
Luigi Caradonna Avatar asked Feb 06 '16 14:02

Luigi Caradonna


1 Answers

fabric.image.fromURL is asyncronous. You have to call the renderAll() inside the callback if you want to show the backgroundimage asap.

Otherwise your mouse click will trigger a renderAll some fraction of second after the load is finished and the background will be rendered.

canvas = new fabric.Canvas('canvas');
canvas.setWidth(660);
canvas.setHeight(590);

    fabric.Image.fromURL('assets/img/materials/marble.bmp', function(image) {
        image.set({
            // I need this because the image size and the canvas size could be different
            // in this way the image always covers the canvas
            width:660,
            height:590
        });

        canvas.setBackgroundImage(image);
        canvas.renderAll();
    });
like image 122
AndreaBogazzi Avatar answered Oct 05 '22 16:10

AndreaBogazzi