Zoom-in zoom-out a sticky point in canvas

Zoom-in zoom-out with stick point is a regular use case we meet on design or builder tools such as Figma. In this blog, I will present a basic algorithm to handle it by javascript, HTML and CSS.

Demo

Demonstration

Code step-by-step

Create a container and a scalable item

In this example, I use an div as a scalable item with class “scalable-child” and its container is a div with class “parent”.

Please note for some properties: 

  • Top, left: 0  is the default position
  • Pointer-event: none, because we will add event to parent, if pointer-event !== none the algorithm will be failed.
  • Transform-origin: left top, that makes coordinate origin to calculate the position

 

Add wheel event listener

We will use WheelEvent to handle zoom-in, zoom-out, and moving child.

Note: this example demonstrates only for the trackpad. You need to handle events for hotkeys such as (Ctrl +, Ctr -) or mouse as well.

Firstly, we have isZooming variable to check if zooming or moving the child element. 

Then we calculate the new position and scale for the child element. Left, top, and scale are being used as temperate variables.

And it’s time to focus the algorithm on 2 calculate functions:

Calculate on Zooming

  • On zooming, wheelEvent will return the deltaY as a scale ratio and we can use it to calculate newScale
    • deltaY > 0 => zoom-out
    • deltaY < 0 => zoom-in
  • We the detalScale = e.deltaY * oldScale * 0.01 to control scaling speed

Let’s see the below image to more understand how to calculate the newLeft and newTop variables:

  • Start zooming-in child when mouse is in A point. At that time, we can get some values:
    • e.offsetX: distance between mouse to parent’s left edge
    • e.offsetY: distance between mouse to parent’s top edge
    • left: current child’s left style value
    • top: current child’s top style value
  • Child is scaled from scale ratio to scale’ ratio, and point A go to A’.

So to make A point sticky (with parent), we need to calculate deltaX and deltaY then move child revert with exactly px.

detalX = x’ – x

= x * (scale’ / scale) – x

= x * (scale’ / scale – 1)

= (e.offsetX – left) * (scale’ / scale – 1)

 

detalY = y’ – y

= y * (scale’ / scale) – y

= y * (scale’ / scale – 1)

= (e.offsetY – top) * (scale’ / scale – 1)

 

=> newLeft = left – detalX

newTop = top – detalY

Calculate on Moving

On moving event, we need to calculate only newLeft and newTop values. And we *2  each delta value to increase speed as well.

That’s all we need to handle. I hope it’s helpful. Thank you for watching!

You can view the full source code here.

Comments

Let’s make a great impact together

Be a part of BraveBits to unlock your full potential and be proud of the impact you make.