Scalable Vector Graphics (SVG)

Definition

Scalable Vector Graphics (SVG) are mathematical formulas that represent a graphical image intended for display on a computer monitor or print output. Depending on the image, the file size could be much smaller.

Placed as <img> with width and height set to 300px.
Placed as <img> with width and height set to 75px.
Placed as <img> with width and height set to 25px.

This image (only .5 kb) was created as:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="144px" height="144px" xml:space="preserve">
<rect x="16" y="16" transform="matrix(0.9479 -0.3185 0.3185 0.9479 -18.9959 26.5526)" fill="#3FA2FF" width="111" height="111"/>
<circle fill="#EF4136" cx="71" cy="71" r="65"/>
</svg>

It is possible to interact with SVG through the use of JavaScript (see p. 149 of HTML5: Designing Rich Internet Applications), but at this point I’m not sure how powerful or realistic it is. Because IE8 doesn’t natively support SVG, I’m doing some experiments with the Raphael polyfill, which generates VML for IE and SVG for everyone else.

SVG drawings are made up of one or more XML elements with attributes that describe the element, for example the fill color of a circle. It is possible to set-up Mouse listeners on the individual SVG elements. SVG is ideally suited for logos and other illustrations, especially when you want to take advantage of high pixel ratio (dpi) displays such as Apple’s Retina screens.

For more information, check out SVG’s W3C Standards page.

How to Create SVG Graphics with Adobe Illustrator

You could code them by hand, but you would have more fun driving a nail through your head. Fire up Adobe Illustrator, create your image, and then do a "Save As…" SVG to make your image. Much easier. Don’t have Illustrator? Try Inkscape.

Tips

Saving the SVG File

Before Saving the Image, Clean up your artboard

To crop the artboard tight around your illustration, select all your artwork and then choose the menu command Object / Artboards / Fit to Artwork Bounds.

Set the X and Y coordinates to (0, 0). Round the width and height values up to the closest whole number. This will prevent the scrollbar issue.

  1. Do the stuff in the box above.
  2. File / Save As...
  3. Profile=SVG 1.1
    1. SVG Tiny is for limited capability devices like old cellphones. Certain capabilities are dropped; like gradients, filters, opacity, and masking.
    2. SVG Mobile has more capabilities, but still designed for mobile devices.
    3. Most modern cell phones support SVG 1.1.
  4. If no text is being used, the the "Fonts" section can be ignored. I have had spacing problems when setting the “Type=SVG”, so go with “Convert to Outline” instead. If you need programatic access to the text, then you will have to go with Type=SVG. For most instances the Subsetting should be set to “Only Glyphs Used”; this of course depends on your intended use.
  5. Image Location=Embed
  6. Set the decimal places to 1 (or 2 if you have really fine detail)
Information from Adobe’s Site

This is from http://help.adobe.com/en_US/illustrator/cs/using/WS714a382cdf7d304e7e07d0100196cbc5f-6561a.html

SVG is a vector format that produces high-quality, interactive web graphics. There are two versions of the SVG formats: SVG and Compressed SVG (SVGZ). SVGZ can reduce file sizes by 50% to 80%; however, you cannot edit SVGZ files using a text editor.

When you save artwork in an SVG format, mesh objects are rasterized. In addition, images that have no alpha channel are converted to the JPEG format. Images with an alpha channel are converted to the PNG format. If your document contains multiple artboards and you save to SVG, the active artboard is preserved. You cannot save individual artboards as separate SVG files.

For a video on creating mobile content in Illustrator, see www.adobe.com/go/vid0207.

If the artwork contains any SVG effects, select each item to which an SVG effect has been applied, and move the effect to the bottom of the Appearance panel (just above the Opacity entry). If other effects follow an SVG effect, the SVG output will consist of a raster object. In addition, if the artwork contains multiple artboards, select the artboard you want to export.

Choose File > Save As or File > Save A Copy.

Type a filename, and choose a location for the file.

Choose SVG (*.SVG) or SVG Compressed (*.SVGZ) as the file format, and click Save.

In the SVG Options dialog box, set the desired options and click OK:

SVG Profiles Specifies the SVG XML Document Type Definition for the exported file.

SVG 1.0 and SVG 1.1 Suitable for SVG files that will be viewed on a desktop computer. SVG 1.1 is the full version of the SVG specification, of which SVG Tiny 1.1, SVG Tiny 1.1 Plus, and SVG Basic 1.1 are subsets.

SVG Basic 1.1 Suitable for SVG files that will be viewed on medium powered devices, such as handheld devices. Keep in mind that not all handhelds support the SVG Basic profile. As a result, selecting this option does not guarantee that the SVG file will be viewable on all handhelds. SVG Basic does not support nonrectangular clipping and some SVG filter effects.

SVG Tiny 1.1 and SVG Tiny 1.1+ Suitable for SVG files that will be viewed on small devices, such as mobile phones. Keep in mind that not all mobile phones support the SVG Tiny and SVG Tiny Plus profiles. As a result, selecting either of these options does not guarantee that the SVG file will be viewable on all small devices.

SVG Tiny 1.2 Suitable for SVG files that will be viewed on a variety of devices ranging from PDAs and mobile phones to laptops and desktop computers.

SVG Tiny does not support gradients, transparency, clipping, masks, symbols, patterns, underline text, strike through text, vertical text, or SVG filter effects. SVG Tiny Plus includes the ability to display gradients and transparency, but does not support clipping, masks, symbols, or SVG filter effects.

For additional information on SVG profiles, see the SVG specification on the World Wide Web Consortium (W3C) website (www.w3.org).

Font Type Specifies how fonts are exported:

Adobe CEF Uses font hinting for better rendering of small fonts. This font type is supported by the Adobe SVG Viewer but may not be supported by other SVG viewers.

SVG Does not use font hinting. This font type is supported by all SVG viewers.

Convert To Outlines Converts type to vector paths. Use this option to preserve the visual appearance of type in all SVG Viewers.

Font Subsetting Controls which glyphs (characters of a particular font) are embedded in the exported SVG file. Choose None from the Subsetting menu if you can rely on the necessary fonts being installed on end-user systems. Choose Only Glyphs Used to include only glyphs for text that exists in the current artwork. The other values (Common English, Common English + Glyphs Used, Common Roman, Common Roman+ Glyphs Used, All Glyphs) are useful when the textual content of the SVG file is dynamic (such as server-generated text or user-interactive text).

Image Location Determines whether raster images are embedded directly in the file or linked to the exported JPEG or PNG images from the original Illustrator file. Embedding images increases file size but ensures that rasterized images will always be available.

Preserve Illustrator Editing Capabilities Preserves Illustrator-specific data by embedding an AI file in the SVG file (resulting in a larger file size). Select this option if you plan to reopen and edit the SVG file in Illustrator. Note that if you make manual changes to the SVG data, the changes are not reflected when you reopen the file. This is because Illustrator reads the AI portion of the file, not the SVG portion.

CSS Properties Determines how style attributes are saved in the SVG code. The default method, Presentation Attributes, applies properties at the highest point in the hierarchy, which allows the most flexibility for specific edits and transformations. The Style Attributes method creates the most readable files but may increase the file size. Choose this method if the SVG code will be used in transformations, for example, transformations using Extensible Stylesheet Language Transformation (XSLT). The Style Attributes <Entity References> method results in faster rendering times and reduced SVG file size. The Style Elements method is used when sharing files with HTML documents. By selecting Style Elements, you can then modify the SVG file to move a style element into an external style sheet file that is also referenced by the HTML file; however, the Style Elements option also results in slower rendering speeds.

Decimal Places Specifies the precision of vector data in the SVG file. You can set a value of 1–7 decimal places. A higher value results in a larger file size and increased image quality.

Encoding Determines how characters are encoded in the SVG file. UTF (UnicodeTransformation Format) encoding is supported by all XML processors. (UTF‑8 is an 8‑bit format; UTF‑16 is a 16‑bit format.) ISO 8859‑1 and UTF‑16 encoding do not preserve file metadata.

Optimize For Adobe SVG Viewer Maintains the highest level of Illustrator data while still allowing the SVG file to be manually edited. Select this option to take advantage of faster rendering for features such as SVG filter effects.

Include Adobe Graphics Server Data Includes all information needed for variable substitution in the SVG file.

Include Slicing Data Includes slice locations and optimization settings.

Include XMP Includes XMP metadata in the SVG file. Choose File > Info or use the Bridge Browser to enter metadata.

Output Fewer <tspan> Elements Allows Illustrator to ignore auto-kerning settings during export, which results in a file with fewer <tspan> elements. Select this option to create an SVG file that is more editable and compact. Deselect this option if maintaining the appearance of auto-kerned text is critical.

Use <textPath> Element For Text On Path Exports text on a path as a <textPath> element. However, note that the text may appear differently in the SVG Viewer than it does in Illustrator since this export mode will not always be able to maintain visual parity. In particular, overflow text will be visible in the SVG Viewer.

Show SVG Code Displays the code for the SVG file in a browser window.

Web Preview Displays the SVG file in a browser window.

Device Central Opens the file in Device Central for previewing on a particular mobile phone or device.

This StackOverflow response also goes into detail on the best settings. There was an interesting tidbit in the answer:

Note that linked bitmap images won't display if the SVG is displayed through the <img> tag, because img doesn't allow loading external resources. Furthermore: webkit has a bug that does not display bitmap images within svg files even if you embed them. In short: use a plain <svg> tag if you intend to embed or link bitmap images, don't use <img>.

Finalizing the SVG File

If you are inlining the SVG into your web page, the SVG tag can look like this:

<svg width="115" height="190" viewBox="0 0 115 190">

Compressing

Once you are done with the manual tweaks, run it through SVGO to compress the code.

The Designer's Guide to Working with SVG Pt.1 has more information on creating and tweaking SVG files.

SVG: Deep Dive

For an in-depth discussion of the specifics of the SVG format, check out the SVG Essentials/Coordinates eBook from O’Reilly.

<svg> attributes

Viewbox: Specified by the width and height attributes. Space taken up on the screen.

viewport: Specifies the canvas size for the internal drawing routines. This is not the actual size shown to the user.

preserveAspectRatio: Comes into play when the aspect ratio of the viewbox and viewport do not match. This is NOT a cure for maintaining aspect ratio on the webpage. This will not be used if you are using a program like Adobe Illustrator to create your SVG (nor should you manually add it in later).

Placing on a Page

First, SVG is not supported in IE8, but all is not lost; stick SVGWeb on your page and you should be fine. You may also need to define the mime-types on your web server. For Apache, put these two lines in your .htaccess file.

AddType image/svg+xml svg svgz

AddEncoding gzip svgz

HTML options

<!-- 1. Using an image tag -->
<img src="mySVG.svg" width="100" height="100">

<!-- 2. Using an object tag -->
<object data="mySVG.svg" width="100" height="100" type="image/svg+xml">
	<!-- alternate content -->
</object> 

<!-- 3. Using an iframe tag -->
<iframe src="mySVG.svg" width="100" height="100"> 

<!-- 4. Direct placement with svg tag -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="144px" height="144px" xml:space="preserve">
	<!-- Your gfx statements go here -->
</svg>

<img> tag

Summary: Good method for placing SVG on a page.

Pros Cons
In Dreamweaver, you will see a box where the SVG will appear (just a grey box, not the actual image unfortunately.) Must manually type the HTML in Dreamweaver's code view.
You easily specify the size you want with the width and height attributes of the <img> tag. If the pixel dimensions of the SVG file are not the same as what you want displayed on the page, you will manually need to compute the new width and height values (in order to keep the same aspect ratio).
Displays well under Safari, Chrome, Firefox  

To specify a back-up image for browsers that do not support SVG in the <img> tag you could do this:

<img src="foo.svg" onerror="this.src=foo.png">

If you want the graphic to be responsive, handle it similarly to the way you would a standard image. In other words, do not include the width and height attributes—let those come from the SVG source. Then apply a CSS width. To prove this concept, see this page.


<object> tag

Summary: Do not use.

Pros Cons
Displays well with Firefox Must manually type the HTML in Dreamweaver's code view.
  Displays poorly with Safari.

<iframe> tag

Summary: Do not use

Pros Cons
Displays well with Firefox, Chrome Must manually type the HTML in Dreamweaver's code view.
  Displays poorly with Safari.

<svg> tag

Summary:Use if you want to style it using CSS or otherwise need access to its DOM. Because you are inlining the SVG into your page, you are eliminating an HTTP Request at the expense of reusability and readability.


CSS Options

Summary: This is a good method for placing SVG on your page; go ahead and use it.

.PxProLogo {
	background:url(PxPro-Logo-optimized.svg);
	background-size:contain; //This will make it fit the box.
	width:182px;
	height:50px; 
}

Snap.svg

Snap.svg is a brand new JavaScript library for working with SVG. Snap provides web developers with a clean, streamlined, intuitive, and powerful API for animating and manipulating both existing SVG content, and SVG content generated with Snap.

Currently, the most popular library for working with SVG is Raphaël. One of the primary reasons Raphaël became the de facto standard is that it supports browsers all the way back to IE 6. However, supporting so many browsers means only being able to implement a common subset of SVG features. Snap was written entirely from scratch by the author of Raphaël (Dmitry Baranovskiy), and is designed specifically for modern browsers (IE9 and up, Safari, Chrome, Firefox, and Opera). Targeting more modern browsers means that Snap can support features like masking, clipping, patterns, full gradients, groups, and more.

Another unique feature of Snap is its ability to work with existing SVG. That means your SVG content does not have to be generated with Snap for you to be able to use Snap to work with it (think "jQuery or Zepto for SVG"). That means you create SVG content in tools like Illustrator, Inkscape, or Sketch then animate or otherwise manipulate it using Snap. You can even work with strings of SVG (for example, SVG files loaded via Ajax) without having to actually render it first which means you can do things like query specific shapes out of an SVG file, essentially turning it into a resource container or sprite sheet.

Finally, Snap supports animation. By providing a simple and intuitive JavaScript API for animation, Snap can help make your SVG content more interactive and engaging. Snap is 100% free and 100% open-source

Comparison to Canvas

Canvas is a relatively new element, while SVG has been around for some time. The difference is canvas was designed for programatic access and it outputs bitmap images (although you can develop with vectors), whereas SVG outputs images from vector data (although it can work with bitmaps).

Given that both Canvas and SVG draw images on the screen, it’s often not immediately clear why you should use one over the other. The two mediums have vastly different approaches. Canvas is an immediate mode API is much like drawing with crayons. You can clear or destroy part of the drawing but you can’t by default revert or alter a previous stroke. Canvas is also a raster bitmap, so it is subject to pixelation when images are scaled. SVG can serve multiple resolutions and pixel densities (dpi) with the same source file; it can also be scripted.

Articles

Using SVG by Chris Coyier (Start with this article)

http://www.html5rocks.com/en/tutorials/svg/mobile_fundamentals/

http://www.inserthtml.com/2013/01/svg-guide-part-1/

A List Apart has a great article explaining how to create an SVG background.

Animation and Tools

Animation is tricky because of cross-browser bugs/inconsitencies. Use GSAP to make it easier. See SVG Animation and CSS Transforms for more information.

This Javascript library claims to help with animating SVG.

Use SVG Optimizer to compress the code.

Use Base64 Encoder if you want to embed the SVG into your CSS.

Styling SVG and Aspect Ratios

Check out this article from Adobe to see how you can use CSS to style your SVG.

For more styling and advanced ways to embed SVG on your page, see my Advanced SVG page.

Using SVG in a CSS "background-image" property

Setting the background size correctly, coverage, and keeping the aspect ratio correct can be quite involved, thankfully it is all detailed out by Mozilla in their Scaling of SVG Backgrounds article.

Fallback for IE8

Because IE8 can not display SVG, you need to create a fallback image such as a PNG to use instead of the SVG. If you have a lot of these to make, or just want it automated as part of the workflow, then the Grunt module “svg2png” is a good option.

If you are using SVGs as inline images, the most robust fallback is to add an inline onerror event to the image tag like this:

<img src="/img/image.svg" onerror="this.src='/img/image.png';this.onerror=null;">

This will swap out the SVG for the PNG image if the SVG fails to load. The extra bit at the end (this.onerror=null;) will stop the event from firing again, which could happen if there was an issue with the path of the PNG. This would then cause an infinite loop of event calls, which is obviously best avoided.

If you are using SVGs as background images in your CSS then there’s a simple way to fall back to PNGs. The support for SVG is roughly in line with support for multiple background images. This means you can use a pure CSS solution, and so the following declarations are all you need:

background: url('/img/image.png') no-repeat; /* works for all browsers */
background: none,
	url('/img/image.svg') no-repeat; /* fails for IE8, and overrides previous statement for current browsers */

Here we are setting a PNG as the background but then overriding it with an SVG for browsers that are able to support multiple backgrounds on the second line.