joriszwart.nl

I code dreams™

SVG

Introduction

Like stated in Creating SVG from 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:
import { draw, setAttributes } from './msvg.js'

const fill = '#CE5127'
const stroke = '#27A2CC'

const svg = document.querySelector('.usage')

svg.append(
    draw('circle', { cx: 50, cy: 75, r: 50, fill }),
    draw('line', { x1: 100, y1: 25, x2: 200, y2: 50, stroke, 'stroke-width': 5 }),
    draw('rect', { x: 150, y: 75, width: 100, height: 50, fill, stroke, 'stroke-width': 5 }),
)
usage.js

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
}
msvg.js

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 })
extend-line.js

Or a function to create a group element:

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

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: lib/esveegee. Still I think a minimalistic library like this has its place.

Attribution

The W3C SVG Logo including a link:

W3C SVG Logo