Assuming you prefer not to utilize Javascript libraries, it seems that you are generating the SVG image in advance or on the server and then delivering static SVG code to users. On the other hand, canvas images are always created using Javascript.
(If you opt to dynamically generate the graph with Javascript without relying on a library, the challenging aspect will be drawing the graph itself rather than resizing it! As mentioned by @Lars Kotthoff, determining the window size and adjusting everything accordingly is simple using Javascript.)
To enable SVG scaling up and down, you must incorporate a viewBox
attribute into your SVG element, which will automatically handle the scaling. However, keep in mind that dynamically sizing the image while maintaining its aspect ratio can be somewhat frustrating. The preserveAspectRatio
attribute prevents distortion but only through the addition of empty space, not scaling down. In Firefox, utilizing height:auto;
will cause the SVG height to adjust to match the width and viewBox aspect ratio, although this behavior may not occur in webkit browsers.
For example:
http://fiddle.jshell.net/9dSbL/
A slightly indirect solution involves:
+ Setting the svg height to a small (but nonzero) value like 1px;
+ Applying overflow:visible;
to the svg;
+ Utilizing a slice
option for preserveAspectRatio
, causing the image to scale according to the larger dimension of height or width;
+ Manually adding a bottom padding style to the svg element that matches the aspect ratio of the viewBox;
+ Enclosing the entire svg within a <div>
with a style of overflow:hidden;
.
For instance:
http://fiddle.jshell.net/9dSbL/1/