Getting started
Preparation
SVG.js assumes you have an HTML element with an id
attribute created and ready to serve as the wrapper. Something like:
<!DOCTYPE html>
<html>
<head>
<title>SVG.js</title>
</head>
<body>
<div id="drawing"></div>
</body>
</html>
Create an SVG document
Next, use the SVG()
function to create an SVG document within the wrapper element:
var draw = SVG('drawing').size(300, 300)
var rect = draw.rect(100, 100).attr({ fill: '#f06' })
The first argument can either be an id of the element or the selected element itself. This will generate the following output:
<div id="drawing">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="300">
<rect width="100" height="100" fill="#f06"></rect>
</svg>
</div>
By default the svg drawing follows the dimensions of its parent, in this case #drawing
:
var draw = SVG('drawing').size('100%', '100%')
Checking for SVG support
By default, SVG.js assumes the client's browser supports SVG. You can test support as follows:
if (SVG.supported) {
var draw = SVG('drawing')
var rect = draw.rect(100, 100)
} else {
alert('SVG not supported')
}
Wait for DOM to be loaded
This might seem obvious to many but it's still worth mentioning. If you include your js files in the head of your document, make sure to wait for the DOM to be loaded:
SVG.on(document, 'DOMContentLoaded', function() {
var draw = SVG('drawing')
})
This is not an issue if you include your js at the bottom.
Pure SVG
SVG.js also works outside of the HTML DOM, inside an SVG document for example:
<?xml version="1.0" encoding="utf-8" ?>
<svg id="drawing" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" >
<script type="text/javascript" xlink:href="svg.min.js"></script>
<script type="text/javascript">
<![CDATA[
var draw = SVG('drawing')
draw.rect(100,100).animate().fill('#f03').move(100,100)
]]>
</script>
</svg>
Playground
Just to get you going, here is a basic setup. Everything is present to start fiddling.