Search code examples
javascriptcanvasfabricjs

How to properly resize the fabricjs without glitches?


I'm using fabricjs, and when I try to resize the whole canvas, I'm having troubles with some things. This is part of my code now:

<div id="cont2" class="cont2">
    <div id="cont" class="container-div-canvas">
        <canvas id="c" width="500" height="428"></canvas>
        <div class="backgroundimage-div" id="bckimg-div"></div>
    </div>
</div>
<script>
document.getElementById("resizecanvasbtn").onclick = () => {
  document.getElementById("cont").style.width = "1000px";
  document.getElementById("cont").style.height = "856px";
  document.getElementById("cont2").style.width = "1000px";
  document.getElementById("cont2").style.height = "856px";
  document.getElementById("c").width = 1000;
  document.getElementById("c").height = 856;
  document.getElementById("c").style.width = "1000px";
  document.getElementById("c").style.height = "856px";
  document.getElementById("bckimg-div").style.width = "1000px";
  document.getElementById("bckimg-div").style.height = "856px";
}
</script>

This is the canvas:

enter image description here

This is the canvas when I resize it: enter image description here

And this is the result when I try to move a component that has been aded before the canvas resizing (the whole glitch is the result of when I move one element arround the canvas): enter image description here

When I add an element after I resize the canvas, it automatically appears on another z-index (I think) and I can't even move it.

I'm not sure where I have the problem, or which thing I'm not having on mind when resizing the canvas.

Any suggestions on where to begin?

Thanks


Solution

  • It results that the document.getElementById("c").width = 1000; does not change the resolution of the canvas at all.

    Instead how it needs to be done is with:

    canvas.setWidth(1000);
    

    That will change not only the canvas but the canvas-container and the upper-canvass divs that fabricjs generates automatically, which leads on the canvas size.

    Hope it helps anybody:)