Graphery SVG

Avatar of Chris Coyier
Chris Coyier on (Updated on )

I’ve compared SVG and Canvas before. If you’re trying to decide between them, read that. I’d say the #1 difference between them is vector (SVG) versus raster (Canvas). But the #2 difference is how you work with them. SVG is declarative, as in, literal elements that express what they are through attributes and content. Canvas is imperative, as in, you script instructions for it to follow.

Canvas is a JavaScript API, so it may jive well with JavaScript developers or environments where the UI being built is otherwise JavaScript-based. But SVG is in the (and has a) DOM, and the DOM has APIs too! That means you can script SVG if you like. It’s just, arguably, not particularly convenient. I just saw Graphery SVG which is clearly an attempt to rectify that.

How you’d script the creation of a pink rectangle with standard DOM APIs:

const div = document.querySelector('#drawing');
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', '100%');
svg.setAttribute('height', '100%');
div.appendChild(svg);
const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect.setAttribute('x', '10');
rect.setAttribute('y', '10');
rect.setAttribute('width', '90');
rect.setAttribute('height', '90');
rect.setAttribute('fill', '#F06');
svg.appendChild(rect);

With Graphery SVG:

const svg = gySVG().width('100%').height('100%');
const rect = svg.add('rect').x(10).y(10).width(90).height(90).fill('#f06');
svg.attachTo('#drawing');

Gotta love that chaining. High five, jQuery.

Direct Link →