Learn Development at Frontend Masters. The following is a guest post by Amelia Bellamy-Royds. Here, she shares an epic guide to scaling SVG, covering all the ways you might want to do that. This year, you are going to start using SVG in your web designs. You create a fabulous header logo in Inkscape and you copy and paste the SVG code it spits out into your WordPress header file.
Until you open up your web page in test browsers and discover that some leave huge blocks of whitespace above and below the image, while others crop it off too short. So, scaling SVG should be easy, right? SVG looks great at any scale, but it can scale in so many different ways that getting it to behave just the way you want can be confusing for SVG beginners.
The image file describes how the browser should color in a grid that is a certain number of pixels wide and a certain number of pixels tall. An important side effect is that raster images have a clearly defined aspect ratio : the ratio of width to height.
You can force the browser to draw a raster image at a different size than its intrinsic height and width, but if you force it to a different aspect ratio, things will get distorted. For this reason, since the early days of the web there has been support for auto scaling on images: you set the height or the width, and the browser adjusts the other dimension so that the aspect ratio stays constant. The following example uses inline SVG, adjusting the dimensions of the element dotted linewithout ever altering the size of the drawn graphic:.
Why does it behave this way? SVG is a document. Same with SVG. By default, it will be drawn at the size specified in the code, regardless of the size of the canvas. What happens if you set the height or width or both to auto for these SVGs? The default size for HTML replaced elements will be used: px wide, px tall. Below, I describe the code you need to get the scale you want for the most common situations:. Other images scale because the browser knows the height, width, and aspect ratio of the image, and it adjusts everything together.
Giving SVG these properties is the first step to getting it to scale. However, scaling SVG goes beyond what is possible with other images. A first glance at the SVG specifications would suggest that the height and width attributes on the top-level svg element will implicitly set an aspect ratio and therefore make SVG scale like other images.
So forget height and width. What you want is to set an aspect ratio for the image, and have the drawing scale to fit. You want a viewBox. The SVG viewBox is a whole lot of magic rolled up in one little attribute.
The viewBox does many things:. Its value is a list of four numbers, separated by whitespace or commas: x, y, width, height. Even if your SVG code uses other units, such as inches or centimeters, these will also be scaled to match the overall scale created by the viewBox.
I'm building a dashboard and using d3. The world. UPDATE: I have scaled the map to an acceptable size for my particular browser sizebut it still will not scale and center when I change the size of the window. IF, however, I resize the window, then hit refresh, then the map will be centered once the page is reloaded.
However, since the scale is static, it is not scaled properly. Here's the solution which will resize the map AFTER the user has released the edge of the window to resize it, and center it in the parent container.
The selection object is an multidimensional array, although in most cases it will probably have only one object in it. That object has a "clientWidth" field that tells you how wide its parent is. The best choice is to have a combined use of aspect ratio on normal definition of d3 graph's width and height.
This has helped me in lot of my graph works. Step 1 : Dynamically get the height of the div to which the graph has to be appended. Step 2 : Declare width as aspect ratio with respect to the dynamically caught height. Learn more.Freightfreedomâ¢
Asked 7 years, 3 months ago. Active 2 years ago. Viewed 63k times. The map is on the page as an SVG container and is rendered using d3. Below are the relevant code slices. Jon Jon 2, 11 11 gold badges 42 42 silver badges 91 91 bronze badges.Nomadic cattle rustler and inventor of the electric lasso.
Company Website Follow me on twitter Contact me for frontend answers. I am available for work right now, if you are interested then email me directly. Following on from my last two posts, Perpendicular Bisectors of a Triangle With d3. You can change the current triangle effects by changing the radio buttons at the top. You can also drag and drop the triangle vertices by dragging the red circles at each triangle endpoint or vertex.
This led to an interesting problem, which was how to how to maintain the current state or coordinates of all the shapes when the user selects a new effect from the radio buttons. Another, more challening problem was to make sure that everything resized to the current ratio or scale if the browser window is resized.
If you go to this url and resize the browser, you can see that everything re-renders nicely to scale. This does not happen out of the box. You need to code for this eventuality. The render function as you might expect, creates the svg document and renders all the shapes onto their specific coordinates as I outlined in the previous blog posts here and here.
I use this function to both initially draw the shapes and also as the function that is attached to the resize event.
Below is the end of the render function that creates a hash that will keep track of the current state of the document or the coordinates of the all the shapes at any given time. Lines 1 to 3 create a the hash and assign the xScale and yScale d3 scale objects that allow you to deal with a finer granuated scale than pixels.
The x and y axis in the documment were created using these scale objects and you can think in terms of placing these objects at coordinates on these scales, e.
Lines 6 to 29 assign properties to this area hash such as the vertices of the triangle that will be used to read and write to when drawing the shapes. I pass this structure into most functions. Line 31 uses the lesser known partial application properties of the bind function to create a new version of the render function.
This partial function when called, will always be called with the area hash as an argument, that contains all the information we need to reconstruct the document.
Line 33 adds this function to the hash, we will use this to remove the event listener each time it is called or else there will be a memory leak. LIne 35 creates an event listener for the resize event and assigns the new version of render to this event. The beginning of the render function below uses the new es6 default paramaters feature to allow render to be called with no arguments or called from the resize event with an argument. If it is called in response to a resize event then there will be a state argument.
Lines 2 to 5 remove the event listener each time it is called. Everytime render is called, I create new xScale and yScale objects that reflect the current window size on line 15 - 21 below:.
If we have a state hash then the invert method of the scale objects is used to get the value in pixels before using the scale to recreate the new x and y coordinates that are in scale with the new browser dimensions. I also use partial application when adding the drag and drop event to the red circles at the vertices of the triangle on line 22 of the below:. After all this, I take great pleasure in resizing the window and watching everything beautifully scale.
The dark mode beta is finally here. Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. You are applying viewBox and preserveAspectRatio to the g element, they need to be applied to the svg element:.
Learn more. Using ViewBox to resize svg depending on the window size Ask Question. Asked 7 years, 4 months ago. Active 4 years ago. Viewed 24k times. Jose Jose 2 2 gold badges 5 5 silver badges 18 18 bronze badges. I have answered a similar question. Active Oldest Votes. Thanks for that. However, if I do this - jsfiddle. Any reasons why? Because your svg variable actually contains a g element, not the SVG.
The dark mode beta is finally here. Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. I'm drawing a scatterplot with d3. With the help of this question : Get the size of the screen, current web page and browser window. Look for 'responsive SVG' it is pretty simple to make a SVG responsive and you don't have to worry about sizes any more. Note: Everything in the SVG image will scale with the window width.
This includes stroke width and font sizes even those set with CSS.
If this is not desired, there are more involved alternate solutions below. Use window. IMO it's better to use select and on since that way you can have multiple resize event handlers It's kind of ugly if the resizing code is almost as long as the code for building the graph in first place.Linux luna
So instead of resizing every element of the existing chart, why not simply reloading it? Here is how it worked for me:.Webplayer us
The crucial line is d3. Otherwise each resizing will add another SVG element below the previous one. However, there's a very simple answer that works for Force Layouts found here. In summary:. In this way, you don't re-render the graph entirely, we set the attributes and d3 re-calculates things as necessary. This at least works when you use a point of gravity. I'm not sure if that's a prerequisite for this solution. Can anyone confirm or deny? This will also handle the case when container is resized because of the nearby elements size change.
There is a polyfill for broader browser support. Something like the following worked for me based on this github issue :. Learn more. Resize svg when window is resized in d3.Easily connect your databases and create powerful visualizations and interactive dashboards in minutes. We've launched a new website to help you understand the data principles you need to get answers today. Scalable Vector Graphics, or SVGis a markup language that describes and generates two-dimensional vector graphics, primarily for the web and viewed on modern browsers.
When developing with SVG, it can often be difficult to scale SVG objects when the containing frame or even the entire browser window changes size. Think of it this way: Images have specific dimensions width and height and thus when a browser displays them or is asked to resize them, it can just automatically adjust the number of pixels in either the x or y axis.
Your computer then recalculates which pixels along those axes should be which colors to best represent that now resized image, discarding the least important pixels in the process. To begin down the road to dynamically resizing SVGs, we need to understand two basic attributes: viewBox and preserveAspectRatio. The viewBox attribute is an essential component to SVG that actually makes them scalable.
It defines the aspect ratio, the inner scaling of object lengths and coordinates, and the axis coordinates x and y for where the SVG should originate. Due to this relationship, preserveAspectRatio requires that the viewBox attribute also be set to function. This forces uniform scaling for both the x and yaligning the midpoint of the SVG object with the midpoint of the container element.
With an understanding of how SVG scaling operates to some degree, we can look at how to scale an SVG chart from a dynamic library like d3.
With that complete, the d3. Login Get started free. Get Started with Chartio. New Learning Platform We've launched a new website to help you understand the data principles you need to get answers today.Plc zero fultek
Learn Data.This chapter looks at the functions D3 provides for taking the effort out of creating vector shapes such as lines:. The shapes in the examples above are made up of SVG path elements. Each of them has a d attribute path data which defines the shape of the path. The path data consists of a list of commands e.
We could create path data ourselves but D3 can help us using functions known as generators. These come in various forms:. We start by constructing a line generator using d3. All lineGenerator has done is create a string of M move to and L line to commands from our array of points.
We can now use pathData to set the d attribute of a path element:. By default each array element represents a co-ordinate defined by a 2-dimensional array e. However we can specify how the line generator interprets each array element using accessor functions.
Now when we call lineGenerator it leaves a gap in the line:. Without configuring. We can also configure how the points are interpolated. For example we can interpolate each data point with a B-spline:. See the curve explorer for more information.
By default the shape generators output SVG path data. However they can be configured to draw to a canvas element using the. Accessor functions. The area generator outputs path data that defines an area between two lines. We can configure the baseline using the. We can also feed a function into the. As with the line generator we can specify the way in which the points are interpolated.