Question

I have an image background in my HTML5 canvas.

var canvas = new fabric.Canvas('#canvas1');
canvas.setBackgroundImage(
            'http://fabricjs.com/assets/jail_cell_bars.png',
             canvas.renderAll.bind(canvas)
       );

How to set dimensions of my canvas (width, height) to the dimensions of the background image?

Thanks.

Was it helpful?

Solution 3

You can use CSS or dom properties to set the dimensions of your canvas. If you know the dimensions of your image, you can do it in a stylesheet:

#canvas1 { width: XXXpx; height: YYYpx; }

Or in the dom:

<canvas id="canvas1" width="XXX" height="YYY"></canvas>

If the image is dynamic and want to set the dimensions in JS, you do something like this:

var image = new Image()
image.src = 'http://fabricjs.com/assets/jail_cell_bars.png';

image.onLoad = function () { 
  var canvas = document.getElementById('canvas1');

  canvas.width = image.width;
  canvas.height = image.height;
};

OTHER TIPS

I think the above answer does not use fabric.js, it uses normal canvas.

When you use fabric.js and its Fabric.Canvas class, the code should be:

image.onLoad = function() {
  var fabric_canvas = new fabric.Canvas('canvas1');
  fabric_canvas.setDimensions({width:image.width, height:image.height});
}; 

In my case,

var canvas = new fabric.Canvas("test_fabric");
canvas.setDimensions({width:800, height:200});

The result is:

<canvas id="test_fabric" width="800" height="200" class="lower-canvas" style="position: absolute; width: 800px; height: 200px; left: 0px; top: 0px; -webkit-user-select: none;"></canvas>

Both canvas.width and canvas.style.width are set.

These work as well!

canvas.setWidth(500);
canvas.setHeight(400);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top