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:
JavaScript
x
3
1
var canvas = this.__canvas = new fabric.Canvas('canvas');
2
canvas.setHeight('100%');
3
canvas.setWidth('100%');
JavaScript
1
7
1
#contCanvasLogo {
2
width: 300px;
3
height: 300px;
4
background: black;
5
}
6
7
#canvas{border:red;}
JavaScript
1
4
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.3.1/fabric.js" integrity="sha512-CzyxOXSECwo2nGJQZ2P8fdDxWVMVzn0jNdT2lYJ3afbqDJbaQ4qxgv9sLc85f6KP8HO2y929Bu+lnPKGC3ofSg==" crossorigin="anonymous"></script>
2
<div id="contCanvasLogo">
3
<canvas id="canvas" class="resize canvasLogo"></canvas>
4
</div>
Advertisement
Answer
You can set the height and width by retrieving the data from the parent container.
JavaScript
1
3
1
canvas.setHeight(document.getElementById("contCanvasLogo").clientHeight);
2
canvas.setWidth(document.getElementById("contCanvasLogo").clientWidth);
3