Set canvas width and height in fabric.js

I have an image 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 the dimensions of my canvas (width, height) to the dimensions of the background image?

Thanks.

+6
source share
2 answers

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

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

Or in dom:

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

If the image is dynamic and you want to set the dimensions in JS, you are doing 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; }; 
+1
source

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}); 

Result:

 <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.

+11
source

All Articles