How to implement zoom and pan (JS)

Does data2viz have out of the box support for zooming and panning?

Typically zooming and panning is implemented by applying transformations on a canvas element:, but this probably wouldn’t work with data2viz, since it would mess up the coordinates in the zoom and drag events.

So, if I have the following Viz:

viz {
    size = size(600, 600)

    circle {
        radius = 5.0
        x = 5.0
        y = 5.0
    circle {
        radius = 5.0
        x = 15.0
        y = 5.0

Does data2viz offer functions (such as zoom(delta: Double) and pan(xOffset: Double, yOffset: Double)) that I can use?

If not, how should I implement this?


Good question!

The way to do panning is to create a group then apply a transform (translate) to it:

group {
     transform {
           translate(xOffset, yOffset)

However, Data2viz only handles 2 AtomicTransformation : translate and rotate, it does not handle a scale transform.

We usually use a scale (Scales.Continuous.Linear in this case) to handle scaling (hence zooming), but as we can’t apply it to the group then it needs to be applied to every size and position of every element!

In your case, having something like:

public data class Scale(
        var scaleX: Double = 1.0, 
        var scaleY: Double = 1.0
): AtomicTransformation

would be very nice, please create an issue on our github, then you can do a PR if you want :wink:

Finally, to handle pan and zoom, you have new KPointerEvents in the last release of D2V, there is a KPointerEvents.zoom that is bound to the mouse wheel by default, giving you the position of the zoom (startZoomPos) and the zoom factor (deltaX and deltaY).

I hope this gives you a lead on where to start.

Thanks for the answer.

I’ve added an issue for the scaling transformation to the data2viz Github.

1 Like