Getting Started With Scalable Vector Graphics (SVG)

Getting Started With Scalable Vector Graphics (SVG)

Tutorial Details
  • Topic: Scalable Vector Graphics
  • Difficulty: Intermediate

As a web designer it’s high time you knew how to implement SVG (Scalable Vector Graphics) into your websites. Let’s now take a look at the basics of SVG, as well as more complex designs such as logos or icons.


What We’ll be Creating

Getting started with SVG
The image above is a screenshot – we’ll be using SVG not images..

Resolution Independent

Recently at WWDC 2012 Apple announced the release of the new retina display MacBook Pro. Retina displays have a higher pixel density (220.5ppi) than that of normal screens or monitors and Apple claim that their retina technology pixel density is so high that the eye is unable to notice pixelation at a typical viewing distance. If you’ve witnessed a retina display firsthand then I’m sure you’ll agree they do look stunning. However, these retina displays can start to cause problems for us web designers.

The problem occurs when images that were previously saved as 72ppi now start to look distorted on retina displays. The solution to this problem is still not 100% solved and designers are looking at new ways to try and get around this problem.

One possible solution (in some cases) is to use SVG. Why would you want to use SVG? SVG’s are rendered as vectors and are therefore able to scale to whatever screen resolution we are viewing them on, whilst maintaining the sharpness and crystal quality that we intended when we first designed them.

This won’t solve all problems; we aren’t able to use SVG to render pixel based images such as .jpg’s or png’s (however, for that we can always use the canvas tag). When it comes to things like illustrated icons or logos then SVG proves extremely useful. Today I’m going to be showing you the basics of using SVG, as well as demonstrating how you can take your vectors that you have designed in Adobe Illustrator and implement them in your websites with ease.


SVG Summed Up in Ten Points

Before we jump in, I’m going to give you a quick overview of SVG:

  • SVG stands for Scalable Vector Graphics.
  • SVG is used to define vector graphics on the web.
  • XML format is used to define the vector graphics.
  • SVG’s do not lose quality when they are resized or zoomed.
  • SVG’s can be animated.
  • SVG integrates with the dom and can work alongside JavaScript and CSS.
  • SVG’s can be indexed, meaning that if you have text in the SVG then search engines will pick this up.
  • SVG’s can be printed at any resolution.
  • SVG is currently a W3C recommendation.
  • SVG works in all modern browsers, though has no support in IE 8 or below. A plugin can be used for anything below that.

Let’s Create Some SVG Shapes

Lines

Let’s start simple. We’ll create a line. We do this by adding the following code to an HTML document.

<svg>
  <line x1="0" y1="0" x2="200" y2="0" style="stroke:rgb(0,0,0);stroke-width:1"/></line>
</svg>

Firstly we use the ‘svg’ tag and then inside that we add the xml markup. Here’s what we’re defining:

  • X1: The start position of the line on the x-axis
  • Y1: The start position of the line on the y-axis
  • X2: The end position of the line on the x-axis
  • Y2: The end position of the line on the y-axis

So for instance, if we wanted to create a diagonal line then we could set the y2 attribute to 200 and this would bring the end point of the line down by 200, therefore creating a diagonal line. We can also apply some styles to this and we do that with CSS. Here we’ve used some inline styles, but you can use them in an external style sheet if you wish.

SVG - Creating a line
<svg>
  <line x1="0" y1="0" x2="200" y2="200" style="stroke:rgb(0,255,255);stroke-width:10"/></line>
</svg>

Circles

Circles can be created in a similar way to a line, with the exception of a few attributes. Here we will create a silver circle, with a black border and a radius of 50.

SVG - Creating a circle
<svg>
	<circle cx="60" cy="60" r="50" stroke="black" stroke-width="5" fill="silver"/>
</svg>

The cx and cy attributes are the ones where we can set the x and y coordinates of the middle of the circle. If we missed out these attributes then the circle’s centre would be set to ’0′ which would result in the circle being cut off from the page. Finally, the attribute marked ‘r’ sets out the radius of the circle.

Rectangles

As you can see by now, creating shapes with SVG really is quite simple. Creating a rectangle is no exception.

SVG - Creating a rectangle
<svg>
<rect width="200" height="100" style="fill:rgb(0,0,255);stroke-width:5"/></rect>
</svg>

In a similar way to setting the width and height of an element in CSS we do the same but using the svg ‘rect’ attributes.

Ellipse

Ellipse works in almost the same way as creating a circle, however, this time rather than just having one fixed radius, we have separate attributes for the x and y radius.

SVG - Creating an ellipse
<svg>
 <ellipse cx="60" cy="60" ry="40" rx="20" stroke="black" stroke-width="5" fill="silver"/></ellipse>
</svg>

Polygons

Polygons get a little bit more tricky (but only a little). We start by giving the polygon a fill color, a stroke of orange and a stroke width of 10. We then pass the point attributes to it. Each pair of coordinates defines the x and y coordinate of each corner point of the polygon. In this demonstration I’ve created a star.

SVG - Creating a polygon star
<svg>
	<polygon fill="green" stroke="orange" stroke-width="10" points="350, 75  379,161 469,161 397,215 423,301 350,250 277,301 303,215 231,161 321,161"/><polygon>
</svg>

Text

As mentioned earlier, SVG is great because when we include text the search engines are able to index it – unlike other rendering engines such as Flash.

This is how we add text:

SVG - Creating text
<text x="0" y="34" style="font-family: Helvetica,Arial,sans-serif;font-weight:bold;font-size:34; fill :#000; ">webdesigntuts+</text>

In the above code you can see that we have added the x and y coordinates. Then set a few CSS styles such as the font-family, weight, size and color.

Paths

Within the path tag we need to concentrate on the ‘d’ attribute. This ‘d’ attribute describes the path to be created. Each command within the ‘d’ attribute is one of the below command letters, followed by its parameters. The commands for the ‘d’ attribute are as follows:

  • M: moveto
  • L: lineto
  • H: horizontal lineto
  • V: vertical lineto
  • C: curveto
  • S: smooth curveto
  • Q: quadratic Bezier curve
  • T: smooth quadratic Bezier curveto
  • A: elliptical Arc
  • Z: closepath
SVG - Creating paths

Here’s some example code:

<svg>
	<path id="path1" d="M160.143,196c0,0,62.777-28.033,90-17.143c71.428,28.572,73.952-25.987,84.286-21.428" style="fill:none;stroke:2;"></path>
</svg>

We can even set our text from above to follow that path like this:

SVG - Creating text
<svg>
	<defs>
		<path id="path1" d="M160.143,196c0,0,62.777-28.033,90-17.143c71.428,28.572,73.952-25.987,84.286-21.428"></path>
	</defs>
	<text x="0" y="34" fill="black" style="font-family: Helvetica,Arial,sans-serif;font-weight:bold;font-size:22; fill :#000; ">
		<textPath xlink:href="#path1">webdesigntuts+</textPath>
	</text>
</svg>

We have basically defined the path in the ‘defs’ tag and given it an id of ‘path1′. We can then apply this to the text using the ‘textPath’ attribute.


Creating a Scalable SVG Logo and Icon

Now that we’ve covered the basics of creating shapes using SVG, it’s time to move on to something a little bit more complex. Fortunately for us though it doesn’t have to be that complex, in fact it’s actually very simple thanks to Adobe Illustrator. For those of you who don’t know about Illustrator, it can be described as:

The industry’s premier vector-drawing environment for creating graphics that scale across media.

Open up Illustrator and create your logo or icon. Most professional logos should have been created using vectors so you should be able to get them from your clients. If not, then you could try recreate them yourself. If you’re not familiar with working in Illustrator then there’s a wealth of information over at Vectortuts+

Once you have your logo or icon, go to “File > Save as”, then select “SVG” from the “Save as type” dropdown. Give your file a name and then click “Save”. The SVG options dialogue should then open. From there select “Show SVG code”. This will then open the code in the browser. You simply need to copy between, and including, the svg tags into your html document and that’s it. How simple was that?

SVG - saving from Adobe Illustrator
SVG - Show code from Adobe Illustrator

You can also use Illustrator to create paths. Simply draw a line in Illustrator, grab the ‘d’ attribute data which you can use for a path as we described earlier. For example, the path that I created for the ‘webdesigntuts+’ text above was created in Illustrator and then exported into my document.

You can then style or position the SVG tag into your document using standard CSS methods. You can also wrap it in an anchor tag to create a link, or target it with JavaScript to add extra functionality.


Conclusion

It’s now only a matter of time before retina and pixel density are part of every device and screen that we use and this will continue to be pushed forward with greater density in the future. By using SVG we are able to create scalable graphics that will render crystal clear and will be ready for the future as screen resolutions get higher. Of course, SVG’s are not practical in every situation, but for vector based illustrations on the web it is most definitely the best way forward.


Additional Resources

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://martealdesigns.com bob marteal

    Thanks! Really useful and clear definition of what SVG is and how to make one. Very happy to see it’s something i can do right out of AI.

  • ne

    Jaw-Dropping Good!
    I’m gonna try this now!

  • http://www.fukava.com hugo andres

    this tut s great explaines very easy what svgs are and makes it very simple for us to use them

    thanks a lot

    somethimes the easiest questions are the hardest to ask

  • Sergey

    Well… nice article. There is one problem… it does not work in ie 8 :)

    • http://www.kieru.com Rob

      Browser short-comings is something that another author covered in a companion article on NetTuts but Aaron really should discuss it (even briefly) here. Maybe I missed it but I didn’t notice any notation or warning that SVG is not cross-browser compatible with all of the major players.

      • Simon

        SVG Summed Up in Ten Points (last point)

        “SVG works in all modern browsers, though has no support in IE 8 or below. A plugin can be used for anything below that.”

  • http://www.suhaildawood.com Suhail Dawood

    Great tutorial! The demo looks amazing on my MacBook Pro with Retina Display!

  • DJ

    Very timely article and I especially appreciated you taking the time to explain the basics of SVG before diving into creating a logo – which ties in to what we learn on VectorTuts+

  • Preston

    I’d say that it’s incredibly irresponsible of Apple to release these displays knowing the problems it will cause without offering a simple solution that doesn’t increase the developer’s workload. In fact, most of what Apple does irresponsibly increases the workload. We have iPhone specific code, iPad specific code, and now MacBook specific code.

    • http://www.suhaildawood.com Suhail Dawood

      Somebody needs to push the market – displays like the Retina Display are the future of devices

    • Chris Janzen

      That is a silly comment. Apples products are just showing how much we have to catch up to the standard. To say that Apple is irresponsible for increasing resolution just shows how irresponsible the designer is. This is only the beginning and we need to be aware of how our websites are displayed. Icon fonts and SVG will become more and more popular.

      • http://www.snaptin.com Ian Yates

        Dead right Chris – to quote Brad Frost: “We don’t know what will be under everyone’s Christmas trees in two years’ time”

        There’s no way we can predict with certainty what the browsing devices of the future will throw at us, so we need to start thinking as flexibly as possible!

  • http://moqups.com Emil

    Ha! We’ve just launched Moqups beta, a nifty wireframing tool entirely based on HTML5 & SVG. Try it out. I think it clearly showcases the potential of using vector graphics in the context of HiDPi screens like Apple’s retina or the printing environments where you also don’t lose quality when upscaling to 300dpi for instance.

  • Techeese

    This is a nice start-up when learning svg, thanks

  • http://enlillebid.dk Joachim

    Great tut!

    But i am wondering about the file-size of svg? is that higher or lower that png?

    if it was to load on 3g network on ipad or mobilephone..

  • Omar

    Hey can you use Inkscape and corel for svg work too?

    • acme

      SVG is Inkscape’s native file format, Corel and others cope with SVG too.

  • http://www.creare-webdesign.co.uk/ Adam Booth

    Great tutorial summing up SVG files superbly. SVG are something I have recently become aware of. I feel they would be great for logos etc. The only worry I would have is the file size. Due to the file size being considerably larger than jpg or png files, would this effect the sites loading speed?
    It is great to see coding to create SVG files, I wasn’t aware that this was possible.
    Great work.

  • http://vector.tutsplus.com Kate

    SVG is great. I would use Inkscape for SVG because it has the best support for the format (and I use Illustrator for my design work almost all of the time).

    Also something to note for people who may work in teams or across different programs. When an SVG file is exported from Illustrator it will create a file containing both valid SVG code and the .AI source code. The dual file is used for easier editing and rendering by Adobe products.

    Because of the dual format, when the file is opened in Inkscape, the image can be edited, but the SVG portion of the file is changed, leaving the .AI portion untouched.

    If you’re using Inkscape and have been given an Illustrator SVG to edit, one workaround for this issue is to open the XML editor in Inkscape and remove all non SVG elements (everything without the svg: prefix). A much easier fix is when exporting an .SVG file from Adobe Illustrator, uncheck the options “Preserve Adobe Illustrator Editing” and “Optimize for Adobe SVG Viewer” in the “Save File” dialogue box. :D

    • http://www.snaptin.com Ian Yates

      Thanks for that Kate :)

  • SlowX

    What are the mobile possibilities/limitations of SVG?

    Does it work on all versions of iOS and Android?

    • http://www.aaronlumsden.com Aaron Lumsden
      Author

      Yes it works on all versions of ios. It is supported on Android 3+ You can see the full support for SVG here http://caniuse.com/svg

      • SlowX

        Awesome, thanks!
        (Stupid Android not supporting SVG until the tablet update, version 3… Here’s hoping ICS comes on strong soon.)

        Also thanks for the link to http://caniuse.com

  • Hamid

    omg! i tho i know what’s SVG! now i see a different meaning of it! fantastic article.!

  • http://www.blackbluebrown.com geoff brown

    Great article. Thank you for brining this versatile format to light.
    Hopefully we’ll start seeing more VGAs in the years to come.
    It’s cool being able to view the ‘source code’ for VGA images too.

  • http://www.blackbluebrown.com geoff brown

    …errr I must need more coffee, I meant SVG, not VGA…. derp.

  • Jack Neary

    Hi,

    Great tutorial! So much so it’s got me trying it out! :)

    But I’ve come up stuck when trying to implement an SVG with a dynamic width in a fluid template…

    Say I have 4 columns, 25% each, and I want to place an SVG in each that will span the full width of the column, and maintain it’s aspect ratio while doing it.

    But the SVG seems to require a height be specified, and assigning both width and height to “100%” just makes the SVG disappear all together?

    I basiclly want to achieve the same effect as giving an image just a width with css, so the height it automatically calculated based on the width and the aspect ratio of the image?

    How would I achieve this result using SVG? any help at all appreciated! :)

    Thanks again!

    Jack

    • Chris Janzen

      Are you using CSS3 Columns? Did you try using column span?

  • Pingback: VEC+ Getting Started With Scalable Vector Graphics (SVG) via buypappa.com | Buypappa blog

  • Chris

    Really nice article, Aaron.

    Loved how you took this seemingly impenetrable topic and made it really easy to digest.

    Keep up the good work.

  • Pingback: Tweet Heat - The hottest Tweets of the Month [June 2012] | Inspired Magazine

  • eddieA

    Sorry if I missed it, but what is the plug in for IE8 and below?

  • Piers

    How do you go about making SVGs responsive? I’ve been trying but having problems with Webkit browsers…

  • Pingback: Getting Started With Scalable Vector Graphics (SVG) | Webdesigntuts+ » Web Design

  • http://www.tutosytips.com/ johanso

    work with SVG for graphics is the best option

  • http://www.dealskey.org.uk uk james

    SVG design is really very nicely created with HTML 5 by someone very creative person. It is totally unique design that I have first seen in this post.

  • Pingback: Hi-Performance Web Design with Data URIs by Chris Brown « Secret Box

  • Adithya

    what i advise is if your are using svg , don’t use illustrator. Rather hand code it . You can manipulate svg with javascript libraries such as jquery and d3

  • Pingback: طراحی سایت با SVG - آموزش طراحی و مدیریت سایت | WEBRGB.NET