gpt4 book ai didi

javascript - 在选中之前,Fabric.js 图像在 Canvas 上不可见

转载 作者:行者123 更新时间:2023-11-29 18:03:04 24 4
gpt4 key购买 nike

我正在创建一个 Canvas ,可以根据用户点击事件向其中添加图像。但是,当单击该元素并添加图像时,图像仍然存在(鼠标悬停表明它存在)但在第二次单击该元素之前在 Canvas 上不可见。

  var canvas = new fabric.Canvas( "designer" );

$( ".shape-option" ).click( function() {
event.stopPropagation();
var shapeSelected = $( this );
var shapeId = shapeSelected.attr( "id" );
var assetObject = new Image();

assetObject.src = "/images/" + shapeId + ".png";
shape = new fabric.Image( assetObject );
shape.set( { top: 0, height: 300, width: 300 } );
canvas.add( shape );
} );

有没有人遇到过这个或类似的问题?

最佳答案

您在触发重新加载的 src 更改后立即执行图像加载,因此当您执行新 fabric.Image 时,元素尚未准备好。

因此,请以其中一种方式更改逻辑:

$( ".shape-option" ).click( function() {
event.stopPropagation();
var shapeSelected = $( this );
var shapeId = shapeSelected.attr( "id" );
var assetObject = new Image();
assetObject.onLoad = function() {
shape = new fabric.Image( assetObject );
shape.set( { top: 0, height: 300, width: 300 } );
canvas.add( shape );
}
assetObject.src = "/images/" + shapeId + ".png";
} );

或者让 fabric 处理异步加载:

$( ".shape-option" ).click( function() {
event.stopPropagation();
var shapeSelected = $( this );
var shapeId = shapeSelected.attr( "id" );
fabric.Image.fromURL('/images/' + shapeId + '.png', function(oImg) {
img.set( { top: 0, height: 300, width: 300 } );
canvas.add(img);
});
} );

关于javascript - 在选中之前,Fabric.js 图像在 Canvas 上不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33529629/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com