JSFiddle - React, Tailwind, and code Playground

by Andrea Bogazzi

HTML

<html>
<body>
<canvas id="canvas"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.1/fabric.js" integrity="sha512-hOJ0mwaJavqi11j0XoBN1PtOJ3ykPdP6lp9n29WVVVVZxgx9LO7kMwyyhaznGJ+kbZrDN1jFZMt2G9bxkOHWFQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</body>
</html>

CSS

body, html {
  width: 100%;
  height: 100%;
  padding: 0px;
  margin: 0px;
}

JavaScript

const canvas = new fabric.Canvas('canvas');
canvas.setWidth(document.body.clientWidth);
canvas.setHeight(document.body.clientHeight);

const CustomObject = fabric.util.createClass(fabric.Image, {
	
  tmpCanvas: null,

  initialize: function(options = {}) {
   	const canvas = document.createElement('canvas'); 
    canvas.width = 500;
    canvas.height = 500;
    this.tmpCanvas = new fabric.Canvas(canvas, { 
      renderOnAddRemove: false 
    });

    this.tmpCanvas.add(new fabric.Text('word 1', {
        left: 100,
        top: 100,
    }));

    //THIS CAUSES THE OFFSET
    this.tmpCanvas.zoomToPoint({
        x: (this.tmpCanvas.width / 2),
        y: (this.tmpCanvas.height / 2),
    }, .5);
    
    //THIS IS WORKING BUT WON'T CENTER IT
/*     this.tmpCanvas.zoomToPoint({
        x: 0,
        y: 0,
    }, .5); */

    this.tmpCanvas.on('after:render', () => {
        this.tmpCanvas.contextContainer.strokeStyle = '#555';
        this.tmpCanvas.contextContainer.save();
				this.tmpCanvas.contextContainer.transform(...this.tmpCanvas.viewportTransform);
        this.tmpCanvas.forEachObject((obj) => {
            var bound = this.getCustomBoundingRect(obj);
            this.tmpCanvas.contextContainer.strokeRect(
                bound.left + 0.5,
                bound.top + 0.5,
                bound.width,
                bound.height
            );
        });
        this.tmpCanvas.contextContainer.restore();
    });

    this.tmpCanvas.renderAll();

    this.callSuper('initialize', canvas, options);
  },

  getCustomBoundingRect: function(obj) {
    const { tl, tr, br, bl } = obj.aCoords || (obj.aCoords = obj.calcACoords());
    let coords = [tl, tr, br, bl];
    if (obj.group) {
      const t = obj.group.calcTransformMatrix();
      coords = coords.map((p) => {
        return fabric.util.transformPoint(p, t);
      });
    }

    let left = 0,
        top = 0,
        width = 0,
        height = 0;

    for (let i = 0, len = coords.length; i < len; i++) {
     ...