JSFiddle - React, Tailwind, and code Playground

by Hooman Askari

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.3.1/fabric.min.js"></script>
  <div class="controls">
    <p>
      <button id="edit" onclick="Edit()">Toggle editing polygon</button>
    </p>
  </div>
  <canvas id="c" width="500" height="400" style="border:1px solid #ccc"></canvas>

CSS

.controls {
  	display: inline-block;
}

JavaScript

var canvas = this.__canvas = new fabric.Canvas('c');
	// create a polygon object
	var points = [{
		x: 3, y: 4
	}, {
		x: 16, y: 3
	}, {
		x: 30, y: 5
	},  {
		x: 25, y: 55
	}, {
		x: 19, y: 44
	}, {
		x: 15, y: 30
	}, {
		x: 15, y: 55
	}, {
		x: 9, y: 55
	}, {
		x: 6, y: 53
	}, {
		x: -2, y: 55
	}, {
		x: -4, y: 40
	}, {
		x: 0, y: 20
	}]
	var polygon = new fabric.Polygon(points, {
		left: 100,
		top: 50,
		fill: '#D81B60',
		strokeWidth: 4,
    stroke: 'green',
		scaleX: 4,
		scaleY: 4,
    flipY: false,
    flipX: false,
		objectCaching: false,
		transparentCorners: false,
		cornerColor: 'blue',
	});
  canvas.viewportTransform = [0.7, 0, 0, 0.7, -50, 50];
	canvas.add(polygon);

	// define a function that can locate the controls.
	// this function will be used both for drawing and for interaction.
	function polygonPositionHandler(dim, finalMatrix, fabricObject) {
	  var x = (fabricObject.points[this.pointIndex].x - fabricObject.pathOffset.x),
		    y = (fabricObject.points[this.pointIndex].y - fabricObject.pathOffset.y);
		return fabric.util.transformPoint(
			{ x: x, y: y },
      fabric.util.multiplyTransformMatrices(
        fabricObject.canvas.viewportTransform,
        fabricObject.calcTransformMatrix()
      )
		);
	}

	// define a function that will define what the control does
	// this function will be called on every mouse move after a control has been
	// clicked and is being dragged.
	// The function receive as argument the mouse event, the current trasnform object
	// and the current position in canvas coordinate
	// transform.target is a reference to the current object being transformed,
	function actionHandler(eventData, transform, x, y) {
		const { target, original } = transform;
    const currentControl = target.controls[target.__corner];
		const mouseLocalPosition = target.toLocalPoint(new fabric.Point(x, y), 'center', 'center');
    
    const originalPoints = original.points;
    let dx = mouseLocalPosition.x - original.mouseDown.x;
    let...