admin管理员组

文章数量:1291214

I am trying to set change the backround image for a canvas using fabric.js but running into some instability. The call to add the background works with no trouble but if I then click anywhere on the canvas it goes blank and seems to move to selection mode - although this just seems to be due to an untrapped exception.

I cannot figure out what is causing the behavior. It works fine on this page / but the following jsfiddle is failing /

var canvas = window._canvas = new fabric.Canvas('c');
canvas.add(new fabric.Circle({ radius: 30, fill: '#f55', top: 100, left: 100 }));
canvas.setBackgroundImage('.png', canvas.renderAll.bind(canvas), {
    backgroundImageOpacity: 0.5,
    backgroundImageStretch: false
});
this.__canvases.push(canvas);

I am trying to set change the backround image for a canvas using fabric.js but running into some instability. The call to add the background works with no trouble but if I then click anywhere on the canvas it goes blank and seems to move to selection mode - although this just seems to be due to an untrapped exception.

I cannot figure out what is causing the behavior. It works fine on this page http://fabricjs./customization/ but the following jsfiddle is failing http://jsfiddle/YH9yD/20/

var canvas = window._canvas = new fabric.Canvas('c');
canvas.add(new fabric.Circle({ radius: 30, fill: '#f55', top: 100, left: 100 }));
canvas.setBackgroundImage('http://fabricjs./assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
    backgroundImageOpacity: 0.5,
    backgroundImageStretch: false
});
this.__canvases.push(canvas);
Share Improve this question asked Apr 14, 2014 at 23:11 Andrew RutterAndrew Rutter 1,2973 gold badges20 silver badges35 bronze badges 1
  • check out this reference link on stack stackoverflow./questions/22877846/… – Sanjay Nakate Commented Apr 15, 2014 at 5:39
Add a ment  | 

2 Answers 2

Reset to default 8

try loading the image before you add to the canvas. if you add an image that hasnt been loaded you will get an exception. This works for us:

var img = new Image();
img.onload = function(){
   canvas.setBackgroundImage(img.src, canvas.renderAll.bind(canvas), {
            originX: 'left',
            originY: 'top',
            left: 0,
            top: 0
        });
};
img.src = "your image source"

regards, Benick

Try this

canvas.setBackgroundImage('add image source', canvas.renderAll.bind(canvas), {
        scaleY: canvas.height ,
        scaleX: canvas.width 
    });

    canvas.renderAll();

本文标签: javascriptSetting a background image in fabricjs throws an exception when clickedStack Overflow