fabric.js 解决图片层级问题和Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported问题

说到fabric.js的层级问题就要说到canvas的数据结构了
canvas.objects是一个数组,里面存储所有的text,image,rect,group等所有元素
首先canvas的层级是先加进来就在下面,后加进来的就在最上面
但是因为图片是异步加载,会因为网络问题最后才加载,然后就覆盖在文字上面了,就出现了图片层级问题

先来介绍fabric.js对于层级给出的方法,可以让元素的层级发生改变

下移:canvas.sendBackwards(canvas.getActiveObject());
上移:canvas.bringForward(canvas.getActiveObject());
置顶:canvas.bringToFront(canvas.getActiveObject());
置底:canvas.sendToBack(canvas.getActiveObject());

先创建创建文字和image:

var canvas=new fabric.Canvas('canvas');
var img=document.createElement("img"); 
img.onload=function(){
    var canvasImage=newfabric.Image(img,{
    left:0,
    top:0,
    width:0,
    height:0
    })
    canvas.add(canvasImage)
}
img.crossOrigin='Anonymous'; 
img.src= 'http://cdn2.jianshu.io/assets/web/logo-58fd04f6f0de908401aa561cda6a0688.png';

var text=new fabric.IText('hello',{
left:0,
top:0,
width:20,
height:20,
fill:'#000',
fontSize:20
})
canvas.add(text)

开始对上面的代码进行修改

var canvas=new fabric.Canvas('canvas');
var img=document.createElement("img");  
img.onload=function(){
    var canvasImage=newfabric.Image(img,{
    left:0,
    top:0,
    width:0,
    height:0,
    zIndex:1
    })
canvas.add(canvasImage)
for(var b=0;b< canvas._objects.length;b++) {
    if(canvasImage.zIndex> canvas._objects[b].zIndex) {
        canvas.bringForward(canvasImage);    //上移
    }else{
        canvas.sendBackwards(canvasImage); //下移
   }
}
})
img.crossOrigin='Anonymous'; //记得加上,不然会出现画布污染(Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported)等错误
img.src= 'http://cdn2.jianshu.io/assets/web/logo-58fd04f6f0de908401aa561cda6a0688.png';

var text=new fabric.IText('hello',{
left:0,
top:0,
width:20,
height:20,
fill:'#000',
fontSize:20,
zIndex:2
})
canvas.add(text)

这样就解决了image层级问题,因为只有图片会出现异步加载,所有只需要针对图片特殊处理就好了,上面的写法也解决了Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported等错误,设置img.crossOrigin='Anonymous';即可解决这个问题。

希望大家喜欢,也希望大家指点错误,也可以加入qq群439667347,大家一起讨论,一起进步,后续更新中...
fabric.js

你可能感兴趣的:(fabric.js 解决图片层级问题和Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported问题)