无法在FabricJS中将图像带到前面

时间:2016-06-13 14:26:33

标签: javascript fabricjs

我有一些麻烦要把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

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

我该怎么办?

2 个答案:

答案 0 :(得分:4)

我不知道为什么,但执行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

答案 1 :(得分:0)

这个问题已经得到了很长时间的回答,但我想我可以添加更多信息,因为我刚刚开始修改FabricJS。

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

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

this Fiddle中查看控制台,看看文字是否在图片之前添加,myText对象在fabric.Image.fromURL回调中是否可用。

相关问题