Skip to content
Advertisement

Fabric js – Set Canvas width and height to 100%

I am using the Fabric js 4.3.1 library and would like to be able to adapt the canvas area to its parent div #contCanvasLogo.

I’ve made a few attempts but nothing works, the canvas keeps resizing by itself. This is my code but not working:

var canvas = this.__canvas = new fabric.Canvas('canvas');
canvas.setHeight('100%');
canvas.setWidth('100%');
#contCanvasLogo {
  width: 300px;
  height: 300px;
background: black;
}

#canvas{border:red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.3.1/fabric.js" integrity="sha512-CzyxOXSECwo2nGJQZ2P8fdDxWVMVzn0jNdT2lYJ3afbqDJbaQ4qxgv9sLc85f6KP8HO2y929Bu+lnPKGC3ofSg==" crossorigin="anonymous"></script>
<div id="contCanvasLogo">
  <canvas id="canvas" class="resize canvasLogo"></canvas>
</div>

Advertisement

Answer

You can set the height and width by retrieving the data from the parent container.

canvas.setHeight(document.getElementById("contCanvasLogo").clientHeight);
canvas.setWidth(document.getElementById("contCanvasLogo").clientWidth);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement