Barbarian Meets Coding
barbarianmeetscoding

WebDev, UX & a Pinch of Fantasy

7 minutes readcreative-codingdraft

Creative Coding

What is creative coding?

Although all coding is a creative endeavor, the term of creative coding normally refers to using code to create art. From wikipedia:

Creative coding is a type of computer programming in which the goal is to create something expressive instead of something functional.

Creative Coding in Wikipedia

An environment for sketching creative coding with Canvas Sketch

Canvas Sketch is a collection of tools, modules and resources for generative art in JavaScript and the browser.* It was created by Matt DesLauriers and provides a mini development environment for doing generative art.

Once you’ve gathered all requirements you can go ahead and install Canvas Sketch from npm (the node.js package manager):

npm install -g canvas-sketch-cli

Once installed run:

canvas-sketch --help
# canvas-sketch -h

To access the Canvas Sketch CLI help and check whether it was installed properly.

Now you can create new sketches using the CLI:

# Creates a new sketch file called my-first-sketch.js
# and starts an http-server with live reload. That is,
# it reloads the browser every time you save your sketch
# JavaScript file
canvas-sketch my-first-sketch.js --new

This command creates a new sketch file called my-first-sketch.js with some boilerplate code:

const canvasSketch = require("canvas-sketch");

const settings = {
  dimensions: [2048, 2048],
};

const sketch = () => {
  return ({ context, width, height }) => {
    context.fillStyle = "white";
    context.fillRect(0, 0, width, height);
  };
};

canvasSketch(sketch, settings);

And starts a live development environment for creative coding. With this development environment you can work on your sketch and see any changes you do immediately reflected in the browser. Once you’re happy with the art that you generate, you can save it as a PNG file using CMD+S (or CTRL+S on Windows and Linux).

For more information take a look at the canvas sketch docs.

Additional libraries

The canvas-sketch-util library is a companion to Canvas Sketch that comes with a number of utility functions and helpers for doing generative art in JavaScript, Canvas and WebGL. For example:

const random = require('canvas-sketch-util/random');

console.log(random.value());
// some random number between 0 (inclusive) and 1 (exclusive)

// Create a seeded random generator
const seeded = random.createRandom(25);

console.log(seeded.range(25, 50));
// some deterministic random number

console.log(seeded.shuffle([ 'a', 'b', 'c' ]));
// deterministically shuffles a copy of the array

You can install with npm:

npm install canvas-sketch-util

Useful CLI arguments

# Run dev environment for existing sketch
canvas-sketch my-first-sketch.js

# Run dev environment and open sketch in the browser
canvas-sketch my-first-sketch.js --open

# By default when saving art (CTRL+S, CMD+S) the generated PNG
# file is saved in the Downloads folder. You can select where to
# store the saved files using the --output flag
canvas-sketch my-sketch-dark.js --output=output/dark

# You can also saved videos from your art. This is specially
# relevant if your art includes animations.
# Save to MP4 file
canvas-sketch animation.js --output=tmp --stream
# Or alternatively as a GIF file
canvas-sketch animation.js --output=tmp --stream=gif

Useful Settings

Canvas sketch offers a myriad of settings to configure your canvas, some of them are:

  • dimensions: Allows to specify the canvas dimensions as width, height or popular print formats like A4, A2, etc.
  • pixelsPerInch: Specify the pixel density of the canvas. e.g. when printing we would want to have a higher pixel denstiy 300.
  • orientation: Allows to define the orientation of the canvas portrait (default), or landscape.

For more available settings take a look at the docs.

Tip: Resolution independent Sketches

When using canvas it is common to paint using drawing primitives in pixels. If we hardcode the number of pixels we use and we later want to have the drawing live in a bigger canvas we’ll be sad to find out that the generated art doesn’t scale. In order to create are that works at any resolution we need to draw using relative units to the total height and width of the canvas:

const sketch = () => {
  return ({ context, width, height }) => {
    context.fillStyle = "white";
    context.fillRect(0, 0, width, height);

    context.lineWidth = width * 0.01; // 1% of the width of the canvas
    const w = width * 0.2;   // 20% of the width of the canvas
    const h = height * 0.2;  // 20% of th height of the canvas
    const x = width * 0.1;   // 10% of the width of the canvas
    const y = height * 0.1;  // 10%...

    context.beginPath();
    context.rect(x, y, w, h);
    context.stroke();
  };
};

Exporting Artwork

Once you’ve started a dev environment with Canvas Sketch you can save your art work using CTLR+S or CMD+S. By default any image that you save will be store in your downloads folder. You can configure this by using the --output flag when initializing your canvas sketch dev environment:

canvas-sketch my-sketch-dark.js --output=output/dark

For exporting videos you’ll need to install ffmpeg:

npm install @ffmpeg-installer/ffmpeg --global

Once installed you can use the --stream flag to enable exporting animations in your artwork. For example:

canvas-sketch animation.js --output=tmp --stream

When your artwork is running as a sketch, you can press CTRL+SHIFT+S or CMD+SHIFT+S to start the recording and use the same key combination to stop the recording.

For more detailed information about exporting artwork with canvas-sketch take a look at the documentation.

Tip: Improved types

To get improved type annotations you may consider installing this additional package: canvas-sketch-types

Resources


Jaime González García

Written by Jaime González García , dad, husband, software engineer, ux designer, amateur pixel artist, tinkerer and master of the arcane arts. You can also find him on Twitter jabbering about random stuff.Jaime González García