Understanding the viewport

I am having difficulty understanding the viewport. Please use the following short program as a reference: Viewport scaling / Gordon Erlebacher / Observable .

Here is an image of the code:

Notice that I specify the width and heigh, even though using Observable’s intrinsic value works.
My question: why is the viewport not set to my speficiations? If I set width and height, I expect a small chart, and that is not what I get. Here is the result when width = height = 10:

However, when width=height=200, here is the chart:

Why is the viewport not the specified size? Where can I find an explanation of this behavior?

Thanks!

Gordon

Hi. As I understand it, what you need is to set the width and height attributes on the svg element to specify its size (you can do it as HTML attributes, or using CSS).

The viewBox attribute is not directly related to the SVG size, and its purpose is to set the “level of zoom”, ie the extent of the part of the SVG that is visible: you might generate a big SVG, but restrict what is shown using the viewBox attribute.
Note also that viewBox is specified in “user units”, which can be… what you want: you might decide to think of the inner coordinates in the SVG as meters, pixels, degrees, or what works better for you. You might then set a circle radius in millimeters, for example, if it makes sense for you. Then specifying viewBox will establish the linear scale between the user units and the browser pixels.

For example, in <svg width=200 height=300 viewBox="-5 -10 20 30" />:

  • the SVG size will be 200x300 pixels
  • the user unit extent (say in meters) will be -5m to 15m horizontally, and -10m to 20m vertically
  • the linear relation is: x_px = (x_user + 5) * 10, y_px = (y_user + 10) * 10. It’s equivalent to setting x=d3.scaleLinear().domain([-5, 15]).range([0, 200]) and y=d3.scaleLinear().domain([-10, 20]).range([0, 300])

The doc on MDN might also help: viewBox - SVG: Scalable Vector Graphics | MDN.

3 Likes