viewBox focus
In a previous article we considered the viewBox attribute and tinkered with a couple of values. We changed
the width of the SVG canvas to focus on a section of a line chart and modified
the origin to scan the chart horizontally.
It is however possible to explore the string further and consider the entire set of numbers, again with practical use cases. And assuredly for silly experiments.
To reintroduce the topic, let me start by updating the past effort. To update the origin of the canvas I asked you to drag a handle, and longed for a true dragging feature. Revisiting pointer events, I tried to accomplish the feat with JavaScript and Svelte, so you won’t have to wish for the experience much longer — feel free to grab and drag the chart to explore the data to your heart’s content.
Focus
Remarkable how it might be, even the draggable line chart updates only one value, the horizontal origin.
<svg viewBox="{x} 0 130 130">
<!-- ... -->
</svg> Behind the scenes, we reduced the width of the canvas, scaling down the value from the measure necessary to show the data in full.
-<svg viewBox="0 0 530 130">
+<svg viewBox="0 0 130 130"> Ultimately we picked an arbitrary value, but if you allow to change the width similarly to the origin, you are able to zoom in the visual with much more freedom.
To prove the concept, let’s forget the line chart and consider a different plot, a scatter plot.
Here we have plenty of points, scattered over two axes, sometimes too close to each other. In terms of viewBox, the attribute sets up a perfectly square canvas 100 units wide and tall.
<svg viewBox="0 0 100 100">
<!-- ... -->
</svg> Change the width and the height, halving both values, and you zoom in in the first quadrant.
-<svg viewBox="0 0 100 100">
+<svg viewBox="0 0 50 50"> Further, modify the origin and you get to explore the rest of the chart. As with the line chart, if you inset the horizontal measure, you move to the right.
-<svg viewBox="0 0 50 50">
+<svg viewBox="50 0 50 50"> Update the vertical component, and you get to move downwards as well.
-<svg viewBox="50 0 50 50">
+<svg viewBox="50 50 50 50"> Finding the four quadrants is then a matter of adjusting the x and y origin. A visual might help.
And with JavaScript and Svelte, an interactive demo is sure to convince you of the usefulness of it all.
Whether you ask readers to pinch the screen and zoom in the visual themselves, as I briefly mentioned in the past article, whether you support dragging, give a handle, or again add a menu to simplify the task, you can rest assured SVG will scale to fit your needs.
And with enough ingenuity and a touch of SMIL animation, the same concept might just delight you with a neat little trick.