scale image by scaling rectangle without group fabric.js

I am new in fabric.js and want to achieve one functionality
I added image and one rectangle same size of image, now I want to scale image while scaling rectangle.
I don’t want to group objects , image should scale by scaling rectangle with previous left, top position of image

below is my code

var imgURL = 'http://i.imgur.com/8rmMZI3.jpg';

var canvas = new fabric.Canvas('canvas');
var pug;
var pugImg = new Image();
pugImg.onload = function (img) {    
    pug = new fabric.Image(pugImg, {
        angle: 0,
        width: 500,
        height: 500,
        left: 50,
        top: 70,
        scaleX: .25,
        scaleY: .25,
        selectable: false
    });
    var rect = new fabric.Rect({
      top: 65,
      left: 200,
      width: 150,
      height: 150,
      fill: 'red',
    });
    canvas.sendToBack(rect);
    canvas.bringToFront(pug);
    
    canvas.add(rect);
    canvas.add(pug);
    canvas.renderAll();
    
};
pugImg.src = imgURL; 
canvas.on('object:scaling', function(e) {
  var bounds = e.target.getBoundingRect();
  pug.set({
    width: bounds.width,
    height: bounds.height,
    top: bounds.top,
    left: bounds.left
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.2.0/fabric.js"></script>
<canvas id="canvas" width=400 height=400></canvas>

17 thoughts on “scale image by scaling rectangle without group fabric.js”

Leave a Comment