I need to build a d3 visualization that works well on both tablets and desktop monitors, and in some cases very large 4k + high-resolution screens.
So, I'm trying to understand what a compromise is between using the SVG attribute 'viewBox' with 'preserveaspectratio' and with the resize function called to re-render on window resize events and use absolute values. Most examples, such as this blog post ( http://eyeseast.imtqy.com/visible-data/2013/08/28/responsive-charts-with-d3/ ), offer the latter in which I am doing something like this:
d3.select(window).on('resize', resize) resize() { // rerender each individual element with the new width+height of the parent node d3.select('svg') .attr('width', newWidth) //etc... and many lines of code depending upon how complex my visualisation is }
However, why can't I just use the SVG viewBox to resize the SVG as follows:
d3.select('svg') .attr( 'preserveAspectRatio',"xMinYMin meet") .attr("viewBox", "0 0 900 500") .attr('width', '100%')
I just do everything, assuming that my width and height are 900x500px (or something else), and use the fact that SVG is a vector format that takes care of all the detailed details, such as text sizes and margins . I'm struggling to understand why so many people, when citing examples of flexible or scalable visualizations using D3, prefer the resize () function, and I'm very worried that I am missing something if I go along the viewBox route.
Edit:
So, in addition to what mef said below, one thought is that with the viewBox I am stuck in a certain aspect ratio. Therefore, I may need to keep the height of the visualization fixed, for example, in the case of a line or a histogram, but it must respond to its width. With a fixed aspect ratio, this is not possible, since changing the width requires a change in height. For this case, the resize () function is required, which is re-attached to the new aspect ratio.
Thus, although a fixed aspect ratio viewBox is much simpler to implement, there are many common cases that require more control, which requires the resize () function and explains the communityβs preference for a more complex solution as the first and last resort. My use case probably favors the viewBox solution, which is a bit unusual when your requirement is responsive.