22

When using 'canvas = new fabric.Canvas('foo')', Fabric converts the canvas element that has a css class with width=100% attached to it into something like that:

<div class="canvas-container" style="position: relative" width="293px">
  <canvas class="upper-canvas"></canvas>
  <canvas class="lower-canvas" id="c"></canvas>
</div>

The wrapping div as well as both canvas elements are getting style tags and fixed width/height. In terms of initialization, I´ve only found canvas.setWdith which only takes numeric values though (no percent values).

Is there a way to initialize Fabric to respect/use the given 100% width?

Update: Example: http://jsfiddle.net/thomasf1/kb2Hp/

thomasf1
  • 1,652
  • 3
  • 17
  • 30

3 Answers3

23

resize fabric's canvas by using its object and window innerWidth and innerHeight

(function(){
  var canvas = new fabric.Canvas('app');

  window.addEventListener('resize', resizeCanvas, false);

  function resizeCanvas() {
    canvas.setHeight(window.innerHeight);
    canvas.setWidth(window.innerWidth);
    canvas.renderAll();
  }

  // resize on init
  resizeCanvas();
})();
ilumin
  • 579
  • 8
  • 19
  • 2
    Just in case if someone want to give specific div dimensions canvas.setHeight($('.yourDiv').height()); canvas.setWidth($('.yourDiv').width()); – saad Feb 29 '16 at 10:11
  • If the page needs some time to setup its layout, it makes sense to postpone the call to `resizeCanvas()`. For me, a `window.setTimeout(resizeCanvas, 2000)` worked much more reliably. – Tom Pohl May 29 '20 at 14:48
11

I'm not sure if you can explicitly tell Fabric to use 100% width, but perhaps get the width of canvas-container through $('.canvas-container').width() or document.getElementById('canvas-container').clientWidth, and then using canvas.setWidth on that value? E.g.:

canvas.setWidth($('.canvas-container').width());


Protip: also remember to set this on window resize to prevent any overflow of content.

Albert Xing
  • 4,840
  • 2
  • 19
  • 39
  • small change, but 'canvas-container' is injected as a class, not an id. So it should be '.canvas-container' not '#canvas-container' – Nick Mitchell Oct 31 '16 at 08:35
  • Just to add some detail to Nick Mitchell's comment, Fabric wraps your host canvas in a div with the `canvas-container` class. – pdoherty926 Jan 07 '20 at 15:18
2

Because the nature of canvas element, width and height need be used in pixel. So, Fabric will not use a percent value to canvas.

attribute unsigned long width;
attribute unsigned long height;
rodrigopandini
  • 907
  • 7
  • 17