mattdesl / canvas-sketch

[beta] A framework for making generative artwork in JavaScript and the browser.
MIT License
4.97k stars 393 forks source link

Exporting multiple png #195

Closed Ricard-Garcia closed 5 months ago

Ricard-Garcia commented 7 months ago

Hello,

I am working in a set of postcards and I am using canvas-sketch to automatically generate a batch of 50 of them.

Since I have collected all the random seeds that I want to use in an array I was wondering whether a sketch could iterate through it and export a file (png in this case) for each of them.

I have been looking for documentation on this but I couldn't find it.

Thanks a lot beforehand.

mattdesl commented 5 months ago

Hi @Ricard-Garcia yes this is possible, and something I do pretty often. Here's how it can be achieved:

import canvasSketch from 'canvas-sketch';
import * as random from 'canvas-sketch-util/random.js';

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

const sketch = () => {
  // using the randomness, make sure it's within the scope of
  // the 'sketch' function like so!
  const r = random.value();

  // return a renderer
  return ({ context, width, height }) => {
    context.fillStyle = 'white';
    context.fillRect(0, 0, width, height);

    context.fillStyle = 'red';
    context.fillRect(0, 0, width * r, height);
  };
};

(async () => {
  const seeds = [
    '1234',
    '5122',
    '5232'
  ];
  for (let i = 0; i < seeds.length; i++) {
    const seed = seeds[i];
    // change the random seed
    random.setSeed(seed);
    // load the sketch
    const manager = await canvasSketch(sketch,{
      ...settings,
      // Additionally, I like to export filenames with the seed attached
      // so that I can get back to this state again later
      suffix: `frame-${i}-seed-${seed}`
    });
    // export a frame and wait for async actions to complete
    await manager.exportFrame();
    // destroy the sketch so that we can load another in the next tick
    manager.destroy()
  }
})();