In this article

When creating a canvas using fabric.js, you can specify the width and height of the canvas in the parameters.

In addition to initialization Settings, fabric.js provides other apis for later modification of the canvas width and height.

This article lists three APIS for fabric.js that set the canvas width and height.

These three apis, while simple, can be important in real life development. For example, listen to the browser window zoom, dynamically adjust the width and height of the canvas.

If you want to get started with fabric.js, see Fabric.js from Getting Started to Expanding.





The environment that

Chrome version: 96.0.4664.45

Fabric.js version: 4.6.0

I developed in a native environment and also provided a copy of the code developed in the Vue3 environment (link at the end of this article).





The actual operation

This example uses three apis:

  • Canvas. setWidth: Sets the canvas width
  • Canvas. setHeight: Sets the canvas height
  • Canvas. SetDimensions: Sets the Canvas size
<style>
  .btn-x {
    margin-bottom: 10px;
  }
  #canvasBox {
    border: 1px solid #ccc;
  }
</style>


<div class="btn-x">
  <button onclick="setWidth(200)">The width of 200 px</button>
  <button onclick="setHeight(300)">Height of 300 px</button>
  <button onclick="setDimensions(600, 400)">One click to set the width and height: 600px width and 400px height</button>
</div>
<canvas id="canvasBox" width="600" height="600"></canvas>


<script src="https://cdn.bootcdn.net/ajax/libs/fabric.js/460/fabric.min.js"></script>
<script>

  let canvas = null

  // Set the canvas width
  function setWidth(width) {
    canvas.setWidth(width)
  }

  // Set the canvas height
  function setHeight(height) {
    canvas.setHeight(height)
  }

  // Set width and height with one click
  function setDimensions(width, height) {
    canvas.setDimensions({
      width,
      height
    })
  }

  window.onload = function() {
    // Create a canvas with the element ID, which you can box on the canvas
    canvas = new fabric.Canvas('canvasBox', {
      width: 100.height: 100})}</script>
Copy the code





Warehouse and recommended reading

warehouse

  • The native implementation sets the canvas width and height

  • The Fabric implementation is used in Vue3 to set the canvas width and height


Recommended reading

  • Fabric.js from Getting Started to Mastering

  • Fabric.js implement Gradient effects, including radial Gradient radial

  • Fabric.js Custom Right-click menu

  • 3 ways to change an image in fabric.js (including changing an image in a group, and if there is a cache)