Search code examples
drag-and-dropangular7pinchzoomangular-material-7angular-material-8

Drag and drop with pinch zoom doesn't work as expected


In the zoomed mode for pinch-zoom the drag doesn't align properly with the mouse pointer.

I've detailed the problem here:https://stackblitz.com/edit/angular-t7hwqg

I expect the drag to work same way irrespective of the zoom. I saw in version 8 of angular material they have added @Input('cdkDragConstrainPosition') constrainPosition: (point: Point, dragRef: DragRef) => Point, which will solve my problem as in the zoomed mode I can write a custom logic to map the drag properly with pointer, but I can't upgrade to version 8 as there are other parts of the application with version 7.

So if someone can suggest what can be done? Either somehow the drag can be modified and take into account the current amount of zoom, or if I can take 'cdkDragConstrainPosition' from version 8 of material and integrate into my current packages.


Solution

  • I had to manually calculate the updated coordinates something like this:

    Here imageHeight is the width/height of the DOM element and height is the actual image height that was loaded into the DOM element. item is the DOM element to be moved around.

    this.zoomFactorY = this.imageHeight / this.height;
    this.zoomFactorX = this.imageWidth / this.width;
    
    // to be called at every position update
    const curTransform = this.item.nativeElement.style.transform.substring(12,
                             this.item.nativeElement.style.transform.length - 1).split(',');
    const leftChange = parseFloat(curTransform[0]);
    const topChange = parseFloat(curTransform[1]);
    

    and then update the DOM item's location:

    item.location.left = Math.trunc(
      item.location.left + leftChange * (1 / this.zoomFactorX)
    );
    item.location.top = Math.trunc(
      item.location.top + topChange * (1 / this.zoomFactorY)
    );