Resizable SVG
November 18, 2010
I wanted to be able to have an SVG pie chart that resized to the available browser window. This can be done using the viewBox
attribute on the svg tag.
The four parameters to the viewBox attribute set up a new co-ordinate system in the available width and height. Width and height on the svg tag default to 100%, so in this example the canvas we have to paint SVG on is 100% of the width and 100% of the height of the browser window.
The position 250,250 will be at the bottom right of the window, and 0,0 will be at the top left.
We can now draw inside this using normal positional elements, and this will resize if the size of the browser window is changed.
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 250 250"> <defs> <radialGradient id="myRadialGradientGreen" r="65%" cx="0" cy="0" spreadMethod="pad"> <stop offset="0%" stop-color="#00ee00" stop-opacity="1"/> <stop offset="100%" stop-color="#006600" stop-opacity="1" /> </radialGradient> </defs> <defs> <radialGradient id="myRadialGradientOrange" r="65%" cx="0" cy="0" spreadMethod="pad"> <stop offset="0%" stop-color="#ffee00" stop-opacity="1"/> <stop offset="100%" stop-color="#ff6600" stop-opacity="1" /> </radialGradient> </defs> <path id='s0' d='M100,100 L0,100 A100,100 0 0,1 7 61 L100,100' style='stroke:#660000; fill:url(#myRadialGradientGreen);'/> <path id='s1' d='M100,100 L7,61 A100,100 0 0,1 100 0 L100,100' style='stroke:#660000; fill:url(#myRadialGradientOrange);'/> <path id='s2' d='M100,100 L100,0 A100,100 0 0,1 170 170 L100,100' style='stroke:#660000; fill:url(#myRadialGradientGreen);'/> <path id='s3' d='M100,100 L170,170 A100,100 0 0,1 0 100 L100,100' style='stroke:#660000; fill:url(#myRadialGradientOrange);'/> <text x="0" y="50" font-family="Verdana" font-size="24" font-weight="bold" text-anchor="middle" fill="rgb(200,200,200)" transform="rotate(270 10 100)">Example Chart</text> </svg>