Cut a part of background image and drag it as an object in fabric JS

Viewed 143

I am drawing a rectangle by using fabric js with mousemove . I want to cut a part of background Image of canvas which comes inside the area of rectangle and then get the cut part of image as an object and paste it anywhere else on canvas. It is like dragging that cut part.

I tried to do it with clipPath:

var marq_rect, isDown, origX, origY, marqer;

canvas.on('mouse:down', function (o) {
    isDown = true;
    canvas.set({ 'selection': false });
    var pointer = canvas.getPointer(o.e);
    origX = pointer.x;
    origY = pointer.y;
    var pointer = canvas.getPointer(o.e);
    marq_rect = new fabric.Rect({
        left: origX,
        top: origY,
        originX: 'left',
        originY: 'top',
        width: pointer.x - origX,
        height: pointer.y - origY,
        angle: 0,
        fill: 'transparent',
        stroke: 'black',
        strokeDashArray: [2, 2],
        strokeDashOffset: 20,
        strokeWidth: 2,
        transparentCorners: false,
        id: 'marq_rect'
   });
                                
   canvas.add(marq_rect);

   canvas.on('mouse:move', function (o) {
       if (!isDown) return;
       var pointer = canvas.getPointer(o.e);

       if (origX > pointer.x) {
           marq_rect.set({ left: Math.abs(pointer.x) });
       }
       if (origY > pointer.y) {
           marq_rect.set({ top: Math.abs(pointer.y) });
       }

       marq_rect.set({ width: Math.abs(origX - pointer.x) });
       marq_rect.set({ height: Math.abs(origY - pointer.y) });
       
       canvas.requestRenderAll();
  });

  canvas.on('mouse:up', function (o) {
     isDown = false;
     canvas.set({ 'selection': true });
     bg_image.clipPath = marq_rect;
     canvas.requestRenderAll();
  });

It should look like this:

enter image description here

You can see that part of image inside the rect is cut out and can be dragged. It can also be a circle or any other shape instead of rect. Thanks in advance.

0 Answers
Related