In the official Konva demo for “Zoom relative to a pointer”, because the focus is on the mechanism and not the application in the real world, the zoom is applied via a set factor:
var scaleBy = 1.01;
But in the real world that’s not what you want. [By the way, I am not knocking Konva or it’s demo docs – they are intended to show specific techniques without being too detailed. And I am a big Konva fan!]
Why not? Because there will be a points of scale where the magnification makes the diagram too small or too large to be of practical use, and every step of the zoom causes a redraw (ok – Konva cleverly throttles actual drawing but it is still true that your computations will run at every step!).
What’s the alternative? Use an array of zoom factors that you pre-define and will be appropriate for your app. In my demo CodePen I use an array as follows:
let currentScaleIdx = 6; // holds array index of current scale. let scales = [5,4,3,2.5,2,1.5,1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.05];
Variable currentScaleIdx is used to track the index of the scale value in the scales array. When the user zooms in or out, we change the currentScaleIdx appropriately and so set the scale factor to be applied.
The advantages are
- You control the scale steps and limits. Each redraw caused by the user changing the scale has a performance overhead so making the scale changes larger and less incremental can provide a massive reduction in the processing burden of your app.
- If you are drawing a grid or ruler then you can work with finite scale values that give predictable behaviour for your ruler/grid drawing & labelling algorithms.
- When the start or the end of the array is reached we can show some UI feedback.
The sample code is based on the original Konva demo, enhanced to use the scales array technique.
VW Dec 2021
You may also be interested in Konva – a better grid which uses this approach and includes a number of solutions for drawing a grid over the Konva stage.