Skip to content
Nim-based DSL allowing to generate SVG files and GIF animations.
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
docs added api docs Sep 19, 2017
examples another spinner Sep 19, 2017
src
tests added tests for path handling Sep 18, 2017
.gitignore improved animation example Aug 16, 2017
.travis.yml split tests Aug 19, 2017
README.md
nimsvg.nimble another spinner Sep 19, 2017
watch.sh another spinner Sep 19, 2017

README.md

NimSvg Build Status

Nim-based DSL allowing to generate SVG files and GIF animations.

DSL

NimSvg is inspired by Karax, and offers a similar DSL to generate SVG trees. A simple hello world

import nimsvg

buildSvgFile("examples/basic1.svg"):
  svg(width=200, height=200):
    circle(cx=100, cy=100, r=80, stroke="teal", `stroke-width`=4, fill="#DDD")

produces the following SVG:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="200" height="200">
  <circle cx="100" cy="100" r="80" stroke="teal" stroke-width="4" fill="#DDD"/>
</svg>

Output:

basic1

The DSL allows to mix tag expressions with regular Nim expressions like variable definitions, for loops, or if statements, which makes it easy to generate SVGs programmatically:

import nimsvg, ospaths, random

buildSvgFile("examples" / sourceBaseName() & ".svg"):
  let size = 200
  svg(width=size, height=size):
    for _ in 0 .. 1000:
      let x = random(size)
      let y = random(size)
      let radius = random(5)
      circle(cx=x, cy=y, r=radius, stroke="#111122", fill="#E0E0F0", `fill-opacity`=0.5)

Output:

basic2

NimSvg also allows to render a sequence of SVG files into an animated GIF (requires Imagemagick for the rendering):

import nimsvg, ospaths

let numFrames = 100
let settings = animSettings().backAndForth(true)

buildAnimation("examples" / sourceBaseName(), numFrames, settings) do (i: int) -> Nodes:
  let w = 200
  let h = 200
  buildSvg:
    svg(width=w, height=h):
      let r = 0.4 * w.float * i.float / numFrames.float + 10
      circle(cx=w/2, cy=h/2, r=r, stroke="#445", `stroke-width`=4, fill="#EEF")

Output:

animation1

Special syntax

  • t: The t keyword can be used to create text nodes:

    let svg = buildSvg:
      text(x=0, y=0):
        t "Hello World"
  • embed: The embed keyword can be used to embed the result of other nodes.

    proc sub(): Nodes = buildSvg:
      b()
      c()
    
    let svg = buildSvg:
      # produces tags <a><b><c><d>
      a()
      embed sub()
      d()

Gallery

Click on an image to see the corresponding implementation.

spinner1

spinner2

spinner3

You can’t perform that action at this time.