p5.js Session 14: Saving Your Sketch

Build one sketch from everything so far, then get it out of the browser with saveCanvas() and a key press.

Thirteen sessions in, everything we have drawn has lived and died inside the browser. This one gets a sketch out as a file you can keep, and the sketch we save uses nearly everything the series has covered.

A sketch made of everything so far

A grid, a palette, two triangles per cell, and chance deciding every colour. The palette is Cherry Blossom Bloom, ten colours this time instead of nine.

let palette;
function setup() {
  createCanvas(800, 800);
  noLoop();
  noStroke();
  palette = [
    '#590D22', '#800F2F', '#A4133C', '#C9184A', '#FF4D6D',
    '#FF758F', '#FF8FA3', '#FFB3C1', '#FFCCD5', '#FFF0F3'
  ];
}
function draw() {
  background(0);
  let cells = 14;
  let cellSize = 50;
  for (let row = 0; row < cells; row++) {
    for (let col = 0; col < cells; col++) {
      let x = 50 + col * cellSize;
      let y = 50 + row * cellSize;
      fill(palette[floor(random(palette.length))]);
      triangle(x, y, x + cellSize, y, x, y + cellSize);
      fill(palette[floor(random(palette.length))]);
      triangle(x + cellSize, y, x + cellSize, y + cellSize, x, y + cellSize);
    }
  }
}
function keyPressed() {
  if (key === 's' || key === 'S') {
    saveCanvas('cherry-blossom-grid', 'png');
  }
}

The finished sketch in the p5.js editor, a 14 by 14 grid of split squares in ten shades of pink and deep red on black

Saving it with a key press

The last four lines are the whole point of the session.

Depending on your browser, the file either lands in your downloads folder straight away or opens a save dialogue.

What you actually get

The saved file open on the desktop, cherry-blossom-grid.png, 1600 by 1600 pixels

The canvas is 800 by 800. The file is 1600 by 1600.

This matters the moment you want to print something. Run it, press s, and check the dimensions of what comes out before you plan around them.

The scripts in this session were written for p5.js 2.3.2, the version the web editor runs by default.


Next session, we make a sketch move: animation, frame by frame.