Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fabric.js: Canvas with 100% width possible?

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/

like image 434
thomasf1 Avatar asked Mar 05 '13 03:03

thomasf1


People also ask

Which function will get the width of the canvas?

You can get the width and height of a canvas element simply by accessing those properties of the element. For example: var canvas = document. getElementById('mycanvas'); var width = canvas.

Can we change the size of the canvas?

With the Select and Move Tool, click the canvas size label or border to select the canvas. Click the canvas border handles to resize the canvas dynamically. When you drag the border handles without using any keyboard modifiers, the canvas resizes non-uniformly. Hold Shift to constrain the resize proportions.

How do I change the width and height of a dynamic canvas?

To do it, simply set the width and height properties of the Canvas object, and then redraw the canvas contents: Canvas . width = 600 ; Canvas . height = 500 ; drawScreen ();


2 Answers

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(); })(); 
like image 114
ilumin Avatar answered Sep 30 '22 02:09

ilumin


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.

like image 31
Albert Xing Avatar answered Sep 30 '22 02:09

Albert Xing