SVG (Scalable Vector Graphics) is now a valid format to use in modern browsers.
It offers vector graphics inline in HTML and it is simpel to write:
<svg width=”100″ height=”100″ xmlns=”http://www.w3.org/2000/svg”>
<rect x=”0″ y=”0″ width=”50px” height=”50px” fill=”#bbbbbb”></rect>
<circle cx=”25px” cy=”25px” r=”20px” fill=”orange”></circle>
Most people can figure out what is inside the above SVG drawing.
Is is nice to have a vector based inline option in HTML, but how do you get something useful to embed in your content? Well there is great support in the most used vector based drawing packages, like Adobe Illustrator, Sketch (for Mac) and the free Inkscape program. You can also use online SVG gererating drawing packages like: svg-editor.
Using SVG in HTML
SVG has a varity of ways in which it can be used inside HTML:
- Inline as other HTML Elements
- Used in IMG src
- As Object tag
- Used in CSS as background image
- Used directly as Base64 encoded data
The first four are “business as usual” if you have been working with HTML for some time. I want to focus on Base64 encoded data method here.
Any text string can be encoded using “Base64” encoding. To be honest I have never dived into the methodes used to convert a string to Base64 encoded data… I sugges that you Google it if you want to know more about Base64 encoding text.
Sublime package (SB2) “StringEncode” – installing
Inside my editor, Sublime Text, I have a command which Base64 encodes a selected piece of text. You can install the utility from package control, simply open package control and type “Install”, then type “StringEncode” and install it.
Base64 encoding in Sublime text
You then select your SVG and fire up Sublime Text Command Palette (on my Mac version of SB2 it is Shift+Cmd+P) and then enter “Base64” and choose the encode command.
width=’30’ height=’30’><circle cx=’15’ cy=’15’ r=’10’ /></svg>
is converted into:
That is the raw encoded data, but before we can use it as a background, we need to prefix it with some text which tells the browser that the data should
be treated as an inline base64 encoded image. Nothing wild, but to remember it can be tricky (for me anyway):
so in our example we should use:
I should tell you that actually you can use the HTML directly, instead of base64 encoding it first.
Which means that this syntax also can be used:
url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='30' height='30'><circle cx='15' cy='15' r='10' /></svg>");
Here we do not specify that it is
base64 but use
That is it!
Well, that was the quick walk through of how you can use SVG base64 encoded in your HTML documents. Below is a list of great resources where you can find out more.