setBackgroundImage无法与多个功能一起正常工作

时间:2018-07-10 00:56:09

标签: javascript jquery fabricjs

我正在尝试从the Fabric.js tutorialsetBackgroundImage到与按钮相关联的一些图像之一,并且变得有些怪异。基本上,按钮1和3都是缓慢/无响应/需要两次单击才能生效,并且按钮2不想在本地或通过Imgur加载。无论如何,我正在使用Fabric.js 1.7.22版和jQuery 3.3.1版。

var canvas = new fabric.Canvas('canvas');

canvas.setHeight(400);
canvas.setWidth(400);

$("#one").click(function(event) {
  canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png');
  canvas.renderAll();
});

$("#two").click(function(event) {
  canvas.setBackgroundImage('https://i.imgur.com/4Ut8gsw.png');
  canvas.renderAll();
});

$("#three").click(function(event) {
  canvas.setBackgroundImage('https://i.imgur.com/2S08Y3b.jpg');
  canvas.renderAll();
});
canvas {
  border: 1px solid #dddd;
}

button {
  margin-top: 20px;
}
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.min.js"></script>

<canvas id="canvas"></canvas>
<button id="one">
One
</button>

<button id="two">
Two
</button>

<button id="three">
Three
</button>

这是怎么回事?预先感谢。

1 个答案:

答案 0 :(得分:3)

setBackgroundImage接受三个参数。

  1. 网址
  2. 回调
  3. 图像选项。

在回调内调用renderAll()

var canvas = new fabric.Canvas('canvas');

canvas.setHeight(400);
canvas.setWidth(400);

$("#one").click(function(event) {
  canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png',function(){
   canvas.renderAll();
  },{
   width:canvas.width,
   height:canvas.height
  });
});

$("#two").click(function(event) {
  canvas.setBackgroundImage('https://i.imgur.com/4Ut8gsw.png',function(){
   canvas.renderAll();
  },{
   width:canvas.width,
   height:canvas.height
  });
});

$("#three").click(function(event) {
  canvas.setBackgroundImage('https://i.imgur.com/2S08Y3b.jpg',function(){
   canvas.renderAll();
  },{
   width:canvas.width,
   height:canvas.height
  });
});
canvas {
  border: 1px solid #dddd;
}

button {
  margin-top: 20px;
}
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.min.js"></script>

<canvas id="canvas"></canvas>
<button id="one">
One
</button>

<button id="two">
Two
</button>

<button id="three">
Three
</button>