Fabric.js背景仅在单击后出现

Lui*_*nna 5 javascript canvas fabricjs

使用以下代码,我创建了一个Fabric画布

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();
Run Code Online (Sandbox Code Playgroud)

画布已创建,但是除非在画布内部单击,否则不会显示背景图像,因为在画布内部单击时会显示背景。

我正在本地计算机上工作,该应用程序不会在线发布。

您为什么认为我遇到了这个问题?我做错什么了吗?我该如何解决此问题?

And*_*zzi 5

Fabric.image.fromURL 是异步的。如果你想尽快显示背景图像,你必须在回调中调用 renderAll() 。

否则,您的鼠标单击将在加载完成后的几分之一秒内触发 renderAll 并渲染背景。

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();
    });
Run Code Online (Sandbox Code Playgroud)