Javascript Fabric.js背景仅在单击后显示

Javascript Fabric.js背景仅在单击后显示,javascript,canvas,fabricjs,Javascript,Canvas,Fabricjs,使用以下代码,我创建了一个结构画布 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 canv

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

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();
画布已创建,但背景图像不会显示,除非我在画布内单击,因为我在画布内单击时背景会显示

我正在本地机器上工作,应用程序不会在线发布


你为什么认为我有这个问题?我做错什么了吗?如何修复此行为?

fabric.image.fromURL是异步的。 如果要尽快显示背景图像,必须在回调中调用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();
    });

在我的例子中,Safari iOS在20-60%的时间内不会呈现背景(版本
“fabric”:“^4.3.1”
)。等待并没有解决问题。点击画布将激活/渲染背景。在不同的地方添加
renderAll()
并不能解决我的问题。没有在Chrome上出现,只有Safari iOS(当时版本为14.1)

B64解决方法:
删除
fabric.Image.fromURL
,而是向
setBackgroundImage
提供一个b64图像,这对我在所有浏览器中都起到了一致的作用

let myImg=`data:image/jpeg;字符集=utf-8;base64`
this.canvasObj.setBackgroundImage(
myImg,//b64
this.canvasObj.renderAll.bind(this.canvasObj)
);

尝试在回调
函数(image)
-
fabric.image.fromURL
中调用
canvas.renderal()
,可能会异步加载图像,因此在加载图像之前会运行代码的底线。谢谢,这很有效。作为评论,我无法将你的答案设置为正确答案。不客气!没关系,有无数这样的问题;它可能会被一个能找到最佳答案链接的人标记为重复;-)既然
setBackgroundImage()
也是异步的,那么在setBackgroundImage的可选回调参数中调用canvas.renderal()是否更安全?(我希望这个库是友好的。)因为
setBackgroundImage
接收图像对象作为参数不应该是异步的。是吗?
setBackgroundImage
是异步的。它有一个可选的回调第二个参数。也许在早期版本中并非如此——我对织物还不熟悉。我刚才提到它是为了避免别人因为不处理这种细微差别而遇到的麻烦。理论上,在这种情况下,您不需要使用回调,您也可以简单地执行
canvas.backgroundImage=image
并使用renderAll或requestRenderall