【问题标题】:Cannot bring image to front in FabricJS无法在 FabricJS 中将图像置于前面
【发布时间】:2016-10-14 00:33:34
【问题描述】:

我很难将 FarbicJS 元素带到画布的前面。

在浏览了几次网页后,我发现了这篇文章:Control z-index in Fabric.js 但是,它似乎对我的代码完全没有影响。

编辑:this topic 也带来了一些其他的解决方案,但也没有效果。

我可能犯了一个愚蠢的错误,但我不知道在哪里。这是我的代码(至少是相关部分):

//first image, well displayed and functionnal
fabric.Image.fromURL(sourceImg, function(img){
    //don't pay attention to following properties
    img.left = YYY
    img.top = XXX
    img.width = whatever
    img.height = whatever
    img.rega = something

    //big animation part
    img.on('mouseover', function(){
        //blabla
    });
    that.canvas.add(img);
});

//second image (text), not displayed
var myText = new fabric.Text("SI REGA2", {
    //some properties...
    left: YYY //    Here coordonnates of the text are the same
    top: XXX  //    than first image's coordonnates.
    selectable: false,
    hasControls: false,
    hasBorders: false,
    fontSize: 20
});
this.canvas.add(myText); //adding text to the canvas...
this.canvas.bringToFront(myText); //... and bringing back to the front in order to place it over the first image

控制台没有错误,所以我认为一切顺利,但是没有显示文本。或者至少在第一张图片下方。

我该怎么办?

【问题讨论】:

  • 你使用网页浏览器的 F12 吗?
  • 是的,很棒的工具。在这里它没有出现,但我尝试console.log(myText) 并且对象似乎没问题。这就是让我认为文本已添加到画布但低于图像的原因。
  • 嗯...那我只能祝你好运了!或提供小型工作样本以隔离您的错误

标签: javascript fabricjs


【解决方案1】:

我不知道为什么,但是执行canvas.sendToBack(img);,会将文本放在图像前面。 canvas.sendToFront(myText); 不会。所以下面的代码会把文字放在图片前面:

var canvas = new fabric.Canvas('fabric');
canvas.backgroundColor = '#ffffff';
canvas.renderAll();

fabric.Image.fromURL("https://placehold.it/200x200", function(img){
    img.left = 0;
    img.top = 0;
    img.width = 200;
    img.height = 200;

    canvas.add(img);
    //Where the magic happens
    canvas.sendToBack(img);
});

var myText = new fabric.Text("SI REGA2", {
    left: 0,
    top: 0,
    selectable: false,
    hasControls: false,
    hasBorders: false,
    fontSize: 20
});
canvas.add(myText);

JSFiddle

【讨论】:

【解决方案2】:

这个问题早已得到解答,但我想我可以添加更多信息,因为我刚刚开始修补 FabricJS。

这里看到的行为是由于fabric.Image.fromURL() 工作异步(回调函数暗示这一点)。因此,首先将myTextobject 添加到画布中,然后然后添加图像。

FabricJS 通过添加到画布的顺序确定 z-index,因此图像与文本重叠是有意义的。

查看this Fiddle 中的控制台,查看文本是否添加到图像之前,并且myText 对象在fabric.Image.fromURL 回调中可用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-28
    • 2015-12-12
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    相关资源
    最近更新 更多