Skip to content
Advertisement

Adding zoom to a packed circle visualisation using Konva (Scale and reposition from center)

I’m created a packed circle visualisation using d3 and drawing it using Konva. If you click on a circle within the packed circle visualisation, the viewport should zoom to that circle.

Each circle has an event handler attached, which gets called on a click event. There I am calculating the value by which to scale the whole visualisation by, and the values by which to reposition the visualisation by.

I can’t quite seem to get the repositioning values correct. The circle on which the click event occurs should be centered in the viewport after scaling it.

JavaScript

enter image description here

JavaScript
JavaScript
JavaScript

Advertisement

Answer

The task is one of moving the stage position (x, y) so that the center of the target circle is in the middle of the viewport – meaning the HTML canvas element visible bounds.

PosX = (viewPort.width / 2) – (circle.pos.x * scale) PosY = (viewPort.height/ 2) – (circle.pos.y * scale)

And using your code that means:

JavaScript

See working snippet below, only those lines changed.

JavaScript
JavaScript
JavaScript
Advertisement