Graphery SVG

Avatar of Chris Coyier
Chris Coyier on (Updated on )

Try Mailchimp today. MailChimp Tracking Pixel

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('', 'svg');
svg.setAttribute('width', '100%');
svg.setAttribute('height', '100%');
const rect = document.createElementNS('', 'rect');
rect.setAttribute('x', '10');
rect.setAttribute('y', '10');
rect.setAttribute('width', '90');
rect.setAttribute('height', '90');
rect.setAttribute('fill', '#F06');

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');

Gotta love that chaining. High five, jQuery.

Direct Link →