Skip to main content


A small declarative DSL for CanvasRenderingContext2D

Works with
This package works with Browsers
JSR Score
3 weeks ago


Graphics DSL is a small library to help write canvas drawing code in a more declarative style.

The main function of this library is render2d(g, dsl)

  • The first argument is the CanvasRenderingContext2D to draw to.

  • The second one is a structure must be one of the following:

    • An array, this recursively calls render2d on every primitive inside the array, automatically scoping the call with save/restore.

    • An object, this is useful for passing multiple options all in one like strokeStyle, lineWidth, ... This can also be used to easily create custom compund styles

      const LINE_STYLE_1 = {
          strokeStyle: 'royalblue',
          lineWidth: 1,
      const LINE_STYLE_2 = {
          lineWidth: 5,
    • A function, this is how primitives are implemented. This simply gets called with the g passed as input. To create new primitives one can use function currying like the circle function

      export const circle = (x, y, r) => g => {
          g.arc(x, y, r, 0, Math.PI * 2)

This idea is mostly borrowed from the Mathematica Graphics function

Example: Live Interactive Graph

interactive graph screenshot

In this example I show how one can create a pretty decent live interactive graph just using render2d (and some utility functions like rescale)

Built and signed on
GitHub Actions
View transparency log