joriszwart.nl

I code dreams™

Minimalistic SVG library

JavaScript SVG Library

Introduction

Like stated in Simple SVG in Javascript creating SVGs doesn't have to be hard. I want to take this a little further and show how to create a minimalistic SVG library in JavaScript (but any language will do).

Usage

Example usage:

export const group = (elements, name = '') => {
    const group = draw('g', { name })
    group.append(...elements)
    return group
}

Which renders an SVG which contains a circle, a line and a rectangle:

The library itself

The code is almost 15 lines.

const NS = 'http://www.w3.org/2000/svg'

export const draw = (name, attributes = {}) => {
    const element = document.createElementNS(NS, name)
    setAttributes(element, attributes)
    return element
}

export const setAttributes = (element, attributes) => {
    for (const [name, value] of Object.entries(attributes)) {
        element.setAttribute(name, value)
    }
    return element
}

That's all. Can you make it smaller? Faster? Better? Leaner?

Extend it

Create a primitive function to take out the guessing.

export const line = (x1, y1, x2, y2, attributes) =>
    draw('line', { x1, y1, x2, y2, ...attributes })

Or a function to create a group element:

export const group = (elements, name = '') => {
    const group = draw('g', { name })
    group.append(...elements)
    return group
}

No more guessing?

It takes some guessingRTFM to look up the parameters. SVG isn't very consistent (x/y? cx/cy? x1/y1? dx/dy? transform? what me worry?).

To mitigate this I am currently working on a SVG library in TypeScript that takes out the guessing. A preview: esveegee. Still I think a minimalistic library like this has its place.

Attribution

The W3C SVG Logo including a link:

W3C SVG Logo