Fabric set('src',url)不起作用,但是setSrc(url)起作用

时间:2019-06-28 06:59:14

标签: canvas fabricjs

所以我有这两行代码-

  1. canvas.item(0).set('src',url); canvas.renderAll();
  2. canvas.item(0).setSrc(url); canvas.renderAll();

因此,现有的画布在第0层加载了图像。因此,当我使用Solution1时,它应该更改图像。但这并没有反映出来。当我尝试console.log(canvas.item(0))时,它显示url设置为src中的object array属性,但从不反映出来。然后,当我使用Solution2时,它可以工作。但是即使那样,它仍然是越野车。我必须运行Solution2两次,然后显示。有什么问题吗?

1 个答案:

答案 0 :(得分:1)

使用image#setSrc更改图像对象的源,该对象接受回调,然后渲染画布。因此,您无需再次致电setSrc

演示

var canvas = new fabric.Canvas('editorCanvas', {
  backgroundColor: 'white',
  width: 300,
  height: 300
});
var imageObject;
fabric.Image.fromURL('https://picsum.photos/200/200', function(img) {
  img.set({width:200,height:200,scaleX:1,scaleY:1})
  imageObject = img;
  canvas.add(img);
},{crossOrigin:'annonymous'});
var i=0;

function changeSrc(){
  var url = 'https://picsum.photos/200/200?random='+ ++i;
  imageObject.setSrc(url,function(){
    canvas.requestRenderAll();
  },{crossOrigin:'annonymous'})
}
canvas{
  border:1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.7.0/fabric.js"></script>
<button onclick='changeSrc()'>changeSrc</button>
<button onclick='addFilter()'>addFilter</button><br>
<canvas id="editorCanvas"></canvas>