简体   繁体   中英

The background image doesnt appear everytime using Fabric.js

Hi I am using the background image in my example. It appears once if I am reloading the page but doesn't appear if I am running the program again.

I have tried setting the image using setBackgroundImage and then render it. It appears first after refreshing the page but doesn't work afterwards.

The fiddle is here — http://jsfiddle.net/wv9MU/6/

// create a wrapper around native canvas element (with id="c")
var canvas = new fabric.Canvas('canvas');

canvas.setBackgroundImage('http://fabricjs.com/assets/jail_cell_bars.png',function() { 
  canvas.renderAll(); 
});


 canvas.setHeight(400);
 canvas.setWidth(1300);
canvas.renderAll();
// create a rectangle object


document.getElementById('1').addEventListener('click', function (e) {
// create a rectangle1 object
var rect = new fabric.Rect({
  left: 100,
  top: 100,
  fill: 'aqua',

  width: 200,
  height: 200
});

// "add" rectangle1 onto canvas
canvas.add(rect);
rect.lockRotation=true;

 canvas.renderAll();   
 });

canvas.setBackgroundImage('C:\Users\131321\Desktop\abc.jpg', canvas.renderAll.bind(canvas));


document.getElementById('2').addEventListener('click', function (e) {
// create a rectangle2 object
var rect = new fabric.Rect({
  left: 150,
  top: 150,
  fill: 'green',
  width: 50,
  height: 50
});

// "add" rectangle2 onto canvas
canvas.add(rect);
rect.lockRotation=true;
 canvas.renderAll();   
 });

It looks like it's because you're loading a local file, and only when you hit run:

Not allowed to load local resource: file:///C:/UsersY321Desktopabc.jpg (index):1
Error loading file:///C:/UsersY321Desktopabc.jpg 

If I change line 36 to

canvas.setBackgroundImage('http://www.placehold.it/250x250', canvas.renderAll.bind(canvas));

It works every time. http://jsfiddle.net/wv9MU/7/

Try adding UsersY321Desktopabc.jpg to your website folders and link it from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM