Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set width and height of canvas in fabric.js

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.

like image 328
Jcbo Avatar asked Apr 29 '14 19:04

Jcbo


2 Answers

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.

like image 55
Calvin Avatar answered Oct 21 '22 16:10

Calvin


These work as well!

canvas.setWidth(500);
canvas.setHeight(400);
like image 35
Tom Avatar answered Oct 21 '22 16:10

Tom