No description
Find a file
2021-06-10 09:40:23 +02:00
.github/workflows refined github action 2020-08-29 11:46:08 +02:00
docs update docs 2020-08-29 12:51:05 +02:00
examples added embed other svgs example 2020-08-29 12:52:00 +02:00
src make templates non-dirty; fixes #14 2021-05-03 09:31:43 +02:00
tests make templates non-dirty; fixes #14 2021-05-03 09:31:43 +02:00
.gitignore added possibility to embed existing svg files 2020-08-29 12:45:11 +02:00
nimsvg.nimble minor improvement to examples 2020-08-29 12:51:38 +02:00
README.md Update README.md 2021-06-10 09:40:23 +02:00
watch.sh improved animation setting interface 2020-04-19 10:03:01 +02:00

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="#EEF")

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="#EEF"/>
</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, random

buildSvgFile("examples/basic2.svg"):
  let size = 200
  svg(width=size, height=size):
    for _ in 0 .. 1000:
      let x = rand(size)
      let y = rand(size)
      let radius = rand(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

let settings = animSettings("filenameBase", backAndForth=true)
let numFrames = 100

settings.buildAnimation(numFrames) 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()
    

Click on an image to see the corresponding implementation.

spinner1 spinner2 spinner3

Example algorithm visualization of rust-array-stump:

algo-viz-1