resize canvas fabric

canvas resize

by thobn24h

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.0/fabric.js"></script>

<script>
  function resizeCanvas() {

    var canvasObject = document.getElementById("editorCanvas");

    $(canvasObject).width($("#canvasContainer").width());
    $(canvasObject).height($("#canvasContainer").height());

    console.log("width: " + $(canvasObject).width());
    console.log("height: " + $(canvasObject).height());

  }

</script>

<div id="canvasContainer">
  <canvas id="editorCanvas"></canvas>
</div>

CSS

#canvasContainer {
  width: 100%;
  height: 100vh;
  background-color: gray;
}

JavaScript

var canvasObject = document.getElementById("editorCanvas");
// set canvas equal size with div
$(canvasObject).width($("#canvasContainer").width());
$(canvasObject).height($("#canvasContainer").height());

console.log("width: " + $(canvasObject).width());
console.log("height: " + $(canvasObject).height());

canvas = new fabric.Canvas('editorCanvas', {
  backgroundColor: 'white',
  selectionColor: 'blue',
  selectionLineWidth: 2
});

// create a rectangle object
var rect = new fabric.Rect({
  left: 10,
  top: 10,
  fill: 'red',
  width: 150,
  height: 150
});

rect.set({
  transparentCorners: false,
  rotatingPointOffset: 40,
  cornerColor: 'black',
  cornerStrokeColor: 'black',
  borderColor: 'black',
  cornerSize: 12,
  padding: 10,
  cornerStyle: 'circle',
  borderDashArray: [3, 3]
});

// "add" rectangle onto canvas
canvas.add(rect);

var text = new fabric.Text('hello world', {
  left: 10,
  top: 10
});
canvas.add(text);

// Tracking resize windows event
window.addEventListener('resize', resizeCanvas, false);