25

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/

2
  • There seems no way to set the width to 100%, when trying to force it via CSS , Fabric stops working as expected.
    – thomasf1
    Commented Mar 5, 2013 at 4:48
  • 1
    solution - stackoverflow.com/a/8486324/104380
    – vsync
    Commented May 19, 2013 at 13:18

3 Answers 3

26

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();
})();
2
  • 3
    Just in case if someone want to give specific div dimensions canvas.setHeight($('.yourDiv').height()); canvas.setWidth($('.yourDiv').width());
    – saad
    Commented Feb 29, 2016 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
    Commented May 29, 2020 at 14:48
12

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.

2
  • small change, but 'canvas-container' is injected as a class, not an id. So it should be '.canvas-container' not '#canvas-container' Commented Oct 31, 2016 at 8:35
  • Just to add some detail to Nick Mitchell's comment, Fabric wraps your host canvas in a div with the canvas-container class. Commented Jan 7, 2020 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;

Not the answer you're looking for? Browse other questions tagged or ask your own question.