Luigi Caradonna
Luigi Caradonna

Reputation: 1064

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?

Upvotes: 10

Views: 2704

Answers (2)

PotatoFarmer
PotatoFarmer

Reputation: 2994

In my case, Safari iOS would not render the background ~20-60% of the time (version "fabric": "^4.3.1"). Waiting did not resolve. Tapping the canvas would activate/render the background. Adding renderAll() in various places did not resolve it for me. Did not happen on Chrome, only Safari iOS (ver. 14.1 at the time)

B64 workaround:

Dropping the fabric.Image.fromURL and instead providing a b64 image to setBackgroundImage worked for me consistently with all browsers.

let myImg = `data:image/jpeg;charset=utf-8;base64,<- base64 data->`

this.canvasObj.setBackgroundImage(
  myImg, //b64
  this.canvasObj.renderAll.bind(this.canvasObj)
);

Upvotes: 0

AndreaBogazzi
AndreaBogazzi

Reputation: 14741

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();
    });

Upvotes: 5

Related Questions