JSFiddle - React, Tailwind, and code Playground

by jurgenwerk

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.4.0/fabric.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<canvas id="mainCanvas" width="450" height="431"></canvas>
<br>
<img id="asd" width="450" height="431"></div>

JavaScript

function scaleSelection(left = 0, top = 0, width = 100, height = 100, img) {
  // How to manipulate blurred canvas and the image here so that
  // the scaled image won't look zoomed?

  // img.setSrc(blurredCanvas.toDataURL(), function(img) {
  //   ...
  //   fabricCanvas.renderAll();
  // });
}

function blurSelection(left=0, top=0, img=null) {
  if (img) {
    img.cropX = left;
    img.cropY = top;
    fabricCanvas.renderAll();
  } else {
    const image = fabric.Image.fromURL(blurredCanvas.toDataURL(), function (img) {
      img.cropX = left;
      img.cropY = top;
      img.width = 200; // Default
      img.height = 200; // Default
      img.objectCaching = false;
      fabricCanvas.add(img);
      img.bringToFront();
      img.on('moving', function (options) {
        const newLeft = options.target.left;
        const newTop = options.target.top;
        blurSelection(newLeft, newTop, img=options.target);
      });

      img.on('scaling', function (options) {
        const newLeft = options.target.left;
        const newTop = options.target.top;
        const img = options.target;
        scaleSelection(img);
      })
    });
  }
}

function copyCanvas() {
  const objects = fabricCanvas.getObjects();
  const copiedCanvas = fabricCanvas.toCanvasElement();

  const blurredImage = new fabric.Image(copiedCanvas);

  const filter = new fabric.Image.filters.Blur({
    blur: 0.2
  });
  blurredImage.filters.push(filter);
  blurredImage.applyFilters();

  blurredCanvas = new fabric.Canvas(copiedCanvas);
  window.blurredCanvas = blurredCanvas;
  blurredCanvas.add(blurredImage);
  blurredCanvas.renderAll();

  // Just for the inspection of the blurred image
  document.getElementById('asd').src = copiedCanvas.toDataURL();
}

$(function () {
  var fabricCanvas = (window.fabricCanvas = new fabric.Canvas("mainCanvas", {
    preserveObjectStacking: true
  }));

  fabric.Image.fromURL("https://i.imgur.com/pZnE4mU.jpg", function (img) {
    fabricCanvas.sendToBack(img);
  ...