### Start a New Sketch with Global CLI Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/installation.md Example usage after installing the CLI globally. This command creates a new sketch file and opens the development server. ```sh mkdir my-sketches cd my-sketches canvas-sketch sketch.js --new --open ``` -------------------------------- ### Basic WebGL Setup with regl Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/webgl.md Demonstrates setting up a WebGL context for canvas-sketch and clearing the buffer with a specific color using the regl library. Ensure 'regl' is installed. ```javascript const canvasSketch = require('canvas-sketch'); const createRegl = require('regl'); const settings = { // Use a WebGL context instead of 2D canvas context: 'webgl', // Enable MSAA in WebGL attributes: { antialias: true } }; canvasSketch(({ gl }) => { // Setup REGL with our canvas context const regl = createRegl({ gl }); // Create your GL draw commands // ... // Return the renderer function return () => { // Update regl sizes regl.poll(); // Clear back buffer with red regl.clear({ color: [ 1, 0, 0, 1 ] }); // Draw your meshes // ... }; }, settings); ``` -------------------------------- ### Run Development Server Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/installation.md Starts the canvas-sketch development server for an existing sketch file. This command is typically used after installing the CLI globally or locally. ```sh canvas-sketch src/foobar.js ``` -------------------------------- ### Install canvas-sketch-cli Locally Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/installation.md Install the canvas-sketch CLI as a development dependency for a specific project. This is useful for managing project-specific tools. ```sh npm install canvas-sketch-cli --save-dev ``` -------------------------------- ### Install FFmpeg Installer Globally Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/troubleshooting.md Install the FFmpeg installer package globally to make ffmpeg available for animation sequence generation. This may require restarting your terminal. ```sh npm install @ffmpeg-installer/ffmpeg --global ``` -------------------------------- ### Scaffold and Open a New Sketch with npx Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/installation.md Use this command to quickly scaffold a new sketch file, generate a package.json, install dependencies, and open the development server in your browser. Notice the '-cli' suffix when using npx. ```sh mkdir my-sketches cd my-sketches npx canvas-sketch-cli --new --open ``` -------------------------------- ### Importing npm GLSL Modules with glslify Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/webgl.md Demonstrates importing GLSL modules from npm, such as 'glsl-noise', directly into your GLSL code using glslify. Run 'npm install glsl-noise' to install the module. ```javascript const glslify = require('glslify'); const vertex = glslify(` #pragma glslify: noise = require('glsl-noise/simplex/3d'); void main () { ... } `) ``` -------------------------------- ### Manual FFmpeg Command for GIF Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/troubleshooting.md Example of a manual ffmpeg command for generating a GIF from PNG sequences, including options for frame rate, scaling, and palette generation. ```sh ffmpeg -r 24 -i %03d.png -y -vf \ fps=24,scale=256:-1:flags=lanczos,palettegen \ output_palette.png && ffmpeg -i tmp/%03d.png \ -i output_palette.png -y -filter_complex \ "fps=24,scale=256:-1:flags=lanczos[x];[x][1:v]paletteuse" \ output.gif ``` -------------------------------- ### Run Local CLI with npx Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/installation.md After installing the CLI locally, use npx to run the 'canvas-sketch' command within the project. npx will automatically find and execute the locally installed version. ```sh npx canvas-sketch my-sketch.js --open ``` -------------------------------- ### Re-render on Event with Props Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/api.md This example shows how to use the `render` function from props to trigger a re-render of the sketch, for instance, on a click event. ```javascript const sketch = ({ render }) => { // Re-render on click window.addEventListener('click', () => render()); return () => { // ... draw something ... }; }; ``` -------------------------------- ### Manual FFmpeg Command for MP4 Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/troubleshooting.md Example of a manual ffmpeg command for generating an MP4 video from PNG sequences, specifying frame rate, codec, and quality settings. ```sh ffmpeg -framerate 24 -i %03d.png -y -c:v libx264 -profile:v high -crf 20 -pix_fmt yuv420p output.mp4 ``` -------------------------------- ### Install canvas-sketch-cli Globally Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/installation.md Install the canvas-sketch CLI tool globally on your system. This allows you to use the 'canvas-sketch' command directly in your terminal without the '-cli' suffix. ```sh npm install canvas-sketch-cli --global ``` -------------------------------- ### Create a Spinning Rectangle Animation Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/animated-sketches.md This example demonstrates how to create a spinning rectangle animation by enabling the animation loop and using the `playhead` prop to control rotation and thickness. Ensure `animate: true` is set in the settings. ```javascript const canvasSketch = require('canvas-sketch'); const settings = { // Enable an animation loop animate: true, // Set loop duration to 3 duration: 3, // Use a small size for better GIF file size dimensions: [ 256, 256 ], // Optionally specify a frame rate, defaults to 30 fps: 30 }; // Start the sketch canvasSketch(() => { return ({ context, width, height, playhead }) => { // Fill the canvas with pink context.fillStyle = 'pink'; context.fillRect(0, 0, width, height); // Get a seamless 0..1 value for our loop const t = Math.sin(playhead * Math.PI); // Animate the thickness with 'playhead' prop const thickness = Math.max(5, Math.pow(t, 0.55) * width * 0.5); // Rotate with PI to create a seamless animation const rotation = playhead * Math.PI; // Draw a rotating white rectangle around the center const cx = width / 2; const cy = height / 2; const length = height * 0.5; context.fillStyle = 'white'; context.save(); context.translate(cx, cy); context.rotate(rotation); context.fillRect(-thickness / 2, -length / 2, thickness, length); context.restore(); }; }, settings); ``` -------------------------------- ### Inlining GLSL Files with glslify Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/webgl.md Shows how to require GLSL files directly into your JavaScript code using glslify, which processes them into strings. Ensure 'glslify' is installed. ```javascript const shader = require('./cool-shader.frag'); // the processed GLSL source string console.log(shader); ``` -------------------------------- ### Convert Between Video Formats Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/cli.md Utility to convert between MP4 and GIF formats using ffmpeg. Ensure ffmpeg is installed and in your PATH. ```bash canvas-sketch-mp4 anim.mp4 anim.gif ``` -------------------------------- ### Update Globally Installed CLI Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/installation.md If you installed the canvas-sketch-cli globally using the --global flag, re-install it to update to the latest version. ```sh npm install canvas-sketch-cli@latest --global ``` -------------------------------- ### A4 Print Artwork with Canvas-Sketch Source: https://github.com/mattdesl/canvas-sketch/blob/master/README.md This example demonstrates creating an A4 print-ready artwork using canvas-sketch. It sets specific dimensions, resolution, and units, then draws a gradient rectangle with margins. Exported images will match the specified print size at 300 DPI. ```js const canvasSketch = require('canvas-sketch'); // Sketch parameters const settings = { dimensions: 'a4', pixelsPerInch: 300, units: 'in' }; // Artwork function const sketch = () => { return ({ context, width, height }) => { // Margin in inches const margin = 1 / 4; // Off-white background context.fillStyle = 'hsl(0, 0%, 98%)'; context.fillRect(0, 0, width, height); // Gradient foreground const fill = context.createLinearGradient(0, 0, width, height); fill.addColorStop(0, 'cyan'); fill.addColorStop(1, 'orange'); // Fill rectangle context.fillStyle = fill; context.fillRect(margin, margin, width - margin * 2, height - margin * 2); }; }; // Start the sketch canvasSketch(sketch, settings); ``` -------------------------------- ### Update Locally Installed CLI Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/installation.md If you installed the canvas-sketch-cli locally using the --save-dev flag, re-install it to update to the latest version. ```sh npm install canvas-sketch-cli@latest --save-dev ``` -------------------------------- ### Modify Sketch Fill Color Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/installation.md Example of a basic canvas-sketch setup. Modify the 'context.fillStyle' to change the background color of the canvas. This code is typically placed in a .js file within your sketches directory. ```js const canvasSketch = require("canvas-sketch"); const settings = { dimensions: [2048, 2048], }; const sketch = () => { return ({ context, width, height }) => { context.fillStyle = "red"; // <-- Try changing the color context.fillRect(0, 0, width, height); }; }; canvasSketch(sketch, settings); ``` -------------------------------- ### Stream Animations to GIF with Scaling Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/exporting-artwork.md You can also apply FFMPEG options, such as scaling, when streaming animations to GIF files. This example scales the GIF to 512 pixels wide. ```sh canvas-sketch animation.js --output=tmp --stream [ gif --scale=512:-1 ] ``` -------------------------------- ### Avoid Side Effects in Renderer Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/hello-world.md This example demonstrates a common pitfall: introducing randomness directly into the renderer function, which can lead to inconsistent results during re-renders or exports. Avoid such side effects. ```javascript // Not so good ! const sketch = () => { return ({ width }) => { // !!! // This may produce different results in re-renders const startX = Math.random() * width; context.fillRect(startX, 0, 50, 50); }; }; ``` -------------------------------- ### Build Sketch to Website Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/cli.md Generates static HTML and JS files for deployment to web hosting. Supports disabling minification. ```bash canvas-sketch mysketch.js --dir public --build --no-compress ``` -------------------------------- ### Build with Custom HTML and JS Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/cli.md Builds a sketch using a specified HTML template and a bundled JavaScript file. The {{entry}} placeholder in the HTML will be replaced with the script tag. ```bash canvas-sketch src/index.js --html=src/page.html --js=bundle.js ``` -------------------------------- ### Generate New Sketch File Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/hello-world.md Use this command to create a new sketch file named 'hello.js'. ```sh canvas-sketch hello.js --new ``` -------------------------------- ### Live Shader Coding with canvas-sketch-util/shader Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/webgl.md Sets up a WebGL sketch for live shader coding using canvas-sketch-util/shader and glslify, enabling hot-reloading for immediate feedback. Requires 'canvas-sketch-util' and 'glslify'. ```javascript const canvasSketch = require('canvas-sketch'); const createShader = require('canvas-sketch-util/shader'); const glsl = require('glslify'); // Setup our sketch const settings = { context: 'webgl', animate: true }; // Your glsl code const frag = glsl(` precision highp float; uniform float time; varying vec2 vUv; void main () { vec3 color = 0.5 + 0.5 * cos(time + vUv.xyx + vec3(0.0, 2.0, 4.0)); gl_FragColor = vec4(color, 1.0); } `); // Your sketch, which simply returns the shader const sketch = ({ gl }) => { // Create the shader and return it return createShader({ // Pass along WebGL context gl, // Specify fragment and/or vertex shader strings frag, // Specify additional uniforms to pass down to the shaders uniforms: { // Expose props from canvas-sketch time: ({ time }) => time } }); }; canvasSketch(sketch, settings); ``` -------------------------------- ### Create New Sketch from Template Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/installation.md Scaffolds a new sketch using a specific template (e.g., 'three' for Three.js) and opens the development server. ```sh canvas-sketch --new --template=three --open ``` -------------------------------- ### Basic Hello World Sketch Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/hello-world.md This is a fundamental sketch that fills the canvas with pink and draws a white rectangle in the center. It requires importing the canvas-sketch library and defining settings for the artwork dimensions. ```javascript // Import the library const canvasSketch = require('canvas-sketch'); // Specify some output parameters const settings = { // The [ width, height ] of the artwork in pixels dimensions: [ 256, 256 ] }; // Start the sketch const sketch = () => { return (props) => { // Destructure what we need from props const { context, width, height } = props; // Fill the canvas with pink context.fillStyle = 'pink'; context.fillRect(0, 0, width, height); // Now draw a white rectangle in the center context.strokeStyle = 'white'; context.lineWidth = 4; context.strokeRect(width / 4, height / 4, width / 2, height / 2); }; }; // Start the sketch with parameters canvasSketch(sketch, settings); ``` -------------------------------- ### Canvas Sketch CLI Usage Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/cli.md Displays the general usage syntax for the canvas-sketch CLI, including available commands and options. ```bash Usage: canvas-sketch [file] [opts] -- [browserifyArgs] Examples: canvas-sketch my-file.js canvas-sketch --build --dir public/ canvas-sketch --new --template=three --open canvas-sketch src/sketch.js --new Options: --help, -h Show help message --version, -v Display version --new, -n Stub out a new sketch --template, -t Set the template to use with --new, e.g. --template=three or --template=penplot --open, -o Open browser on run --hot Enable Hot Reloading during development --output Set output folder for exported sketch files --dir, -d Set output directory, defaults to '.' --port, -p Server port, defaults to 9966 --no-install Disable auto-installation on run --force, -f Forces overwrite with --new flag --pushstate, -P Enable SPA/Pushstate file serving --quiet Do not log to stderr --build Build the sketch into HTML and JS files --no-compress Disable compression/minification during build --inline When building, inline all JS into a single HTML --name The name of the JS file, defaults to input file name --js The served JS src string, defaults to name --html The HTML input file, defaults to a basic template --stream, -S Enable ffmpeg streaming for MP4/GIF formats --https Use HTTPS (SSL) in dev server instead of HTTP --source-map Source map option, can be false, "inline", "external", or "auto" (default) ``` -------------------------------- ### Build Sketch for Deployment Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/installation.md Builds your canvas-sketch project into a sharable HTML and JavaScript website, suitable for deployment. ```sh canvas-sketch sketches/my-sketch.js --build ``` -------------------------------- ### Use Custom Sketch Template Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/cli.md Creates a new sketch using a specified template file, which can be a built-in template or a custom local file. ```bash canvas-sketch sketch.js --new --template=three --open ``` ```bash canvas-sketch sketch.js --template=./mytemplate.js ``` -------------------------------- ### Build Standalone HTML Website with Canvas-Sketch CLI Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/other-topics.md Use the Canvas-Sketch CLI to build a sketch file into a standalone HTML website. This command bundles the sketch and its dependencies into a single HTML file for easy deployment or local viewing. ```sh canvas-sketch sketch.js --name index --build --inline ``` -------------------------------- ### Run Existing Sketch Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/cli.md Executes an existing sketch file using the development server. Supports hot reloading and specifying output directories. ```bash canvas-sketch mysketch.js ``` ```bash canvas-sketch mysketch.js --hot ``` ```bash canvas-sketch mysketch.js --dir public ``` -------------------------------- ### Build Standalone HTML Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/cli.md Renders a sketch into a single, self-contained HTML file. Use --name to set the output filename. ```bash canvas-sketch mysketch.js --name index --build --inline ``` -------------------------------- ### Run Sketch with Browserify Transforms Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/cli.md Allows specifying custom browserify transforms to be applied when running a sketch. ```bash canvas-sketch mysketch.js -- -t bubleify ``` -------------------------------- ### Create New Sketch Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/cli.md Generates a new sketch file and optionally opens it in the browser. Can also pipe source code directly for creation. ```bash # Make a new sketch file called 'my-sketch.js' and run it canvas-sketch my-sketch.js --new ``` ```bash # Create a sketch and open the browser on start canvas-sketch src/sketch.js --new --open ``` ```bash # Write & launch a sketch from clipboard pbpaste | canvas-sketch --new --open ``` -------------------------------- ### Clear npx Cache for Latest CLI Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/installation.md If you use the npx quick-start method, clear the npx cache to ensure you pick up the latest version of the CLI. After clearing the cache, re-run your command. ```sh npx clear-npx-cache@1.0.1 ``` -------------------------------- ### Configure Print Settings with Units and Bleed Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/physical-units.md Set up canvas-sketch for print by defining `pixelsPerInch`, `units` to 'in', `dimensions`, and `bleed`. This configures the canvas to work with physical measurements for printing. ```javascript const settings = { // Output resolution, we can use 300PPI for print pixelsPerInch: 300, // All our dimensions and rendering units will use inches units: 'in', // Standard business card size dimensions: [ 3.5, 2 ], // Include a bit of 'bleed' to the dimensions above bleed: 1 / 8 }; canvasSketch(() => { // Render the business card return props => { const { context, exporting, bleed, width, height, trimWidth, trimHeight } = props; // Fill entire page with solid color context.fillStyle = '#1d1d1d'; context.fillRect(0, 0, width, height); // Visualize the trim area with a yellow guide (ignored on export) if (!exporting && bleed > 0) { context.strokeStyle = 'yellow'; context.lineWidth = 0.0075; context.strokeRect(bleed, bleed, trimWidth, trimHeight); } // ... rest of sketch ``` -------------------------------- ### Settings Object Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/api.md Details the available settings for configuring the canvas-sketch behavior, including dimensions, units, and scaling options. ```APIDOC ## Settings The `settings` object often looks like this: ```js // 11 x 7 inches artwork const settings = { dimensions: [ 11, 7 ], units: 'in' }; ```
#### Size Settings parameter | type | default | description --- | --- | --- | --- `dimensions` | Array \| String | *window size* | The dimensions of your sketch in `[width, height]` units. If not specified, the sketch will fill the browser window. You can also specify a [preset string](./physical-units.md#paper-size-presets) such as `"A4"` or `"Letter"`. `units` | String | `"px"` | The working units if `dimensions` is specified, can be `"in"`, `"cm"`, `"px"`, `"ft"`, `"m"`, `"mm"`. `pixelsPerInch` | Number | 72 | When `units` is a physical measurement (e.g. inches), this value will be used as the resolution to convert inches to pixels for exporting and rendering. `orientation` | String | `"initial"` | If `"landscape"` or `"portrait"` are specified, the dimensions will be rotated to the respective orientation, otherwise no change will be made. Useful alongside [`dimensions` presets](./physical-units.md#paper-size-presets). `scaleToFit` | Boolean | true | When true, scales down the canvas to fit within the browser window. `scaleToView` | Boolean | false | When true, scales up or down the canvas so that it is no larger or smaller than it needs to be based on the window size. This makes rendering more crisp and performant, but may not accurately represent the exported image. This is ignored during export. `bleed` | Number | 0 | You can pad the dimensions of your artwork by `bleed` units, e.g. for print trim and safe zones. `pixelRatio` | Number | device ratio | The pixel ratio of the canvas for rendering and export. Defaults to `window.devicePixelRatio`. `exportPixelRatio` | Number | `pixelRatio` | The pixel ratio to use when exporting, defaults to `pixelRatio`. Not affected by `maxPixelRatio`. `maxPixelRatio` | Number | Infinity | A maximum value for pixel ratio, in order to clamp the density for Retina displays. `scaleContext` | Boolean | true | When true, 2D contexts will be scaled to account for the difference between `width` / `height` (physical measurements) and `canvasWidth` / `canvasHeight` (in-browser measurements). `resizeCanvas` | Boolean | true | When true, canvas width and height will be set. You can stop the canvas from being resized by setting this to false. `styleCanvas` | Boolean | true | When true, canvas style width and height will be added to account for pixelRatio scaling. Disable this by setting it to false.
``` -------------------------------- ### Canvas-Sketch CLI Commands Source: https://github.com/mattdesl/canvas-sketch/blob/master/README.md A collection of common canvas-sketch-cli commands for managing and building sketches. Includes options for specifying output, using templates, building for web, and enabling hot reloading. ```sh npx canvas-sketch-cli src/foobar.js --output=./tmp/ ``` ```sh npx canvas-sketch-cli --new --template=three --open ``` ```sh npx canvas-sketch-cli src/foobar.js --build ``` ```sh npx canvas-sketch-cli src/foobar.js --hot ``` -------------------------------- ### Use Canvas-Sketch via UMD Build Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/troubleshooting.md Include the canvas-sketch UMD build directly in an HTML file using a CDN like unpkg.com. This attaches the library to the window global. ```html ``` -------------------------------- ### Async Sketch with Image Loading in JavaScript Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/other-topics.md Create an asynchronous sketch that loads an image using the 'load-asset' library. The sketch function returns a Promise that resolves to the renderer, allowing for pre-loading of assets like images before rendering. ```javascript const canvasSketch = require('canvas-sketch'); const load = require('load-asset'); // We create an 'async' sketch canvasSketch(async ({ update }) => { // Await the image loader, it returns the loaded const image = await load('assets/baboon.jpg'); // Once the image is loaded, we can update the output // settings to match it update({ dimensions: [ image.width, image.height ] }); // Now render our sketch return ({ context, width, height }) => { // Draw the loaded image to the canvas context.drawImage(image, 0, 0, width, height); // Extract bitmap pixel data const pixels = context.getImageData(0, 0, width, height); // Manipulate pixel data // ... sort & glitch pixels ... // Put new pixels back into canvas context.putImageData(pixels, 0, 0); }; }); ``` -------------------------------- ### Scaffold a New Sketch with Canvas-Sketch CLI Source: https://github.com/mattdesl/canvas-sketch/blob/master/README.md Use this command to create a new sketch file and automatically open it in your browser. Requires Node.js v15+ and npm v7+. ```sh mkdir my-sketches cd my-sketches npx canvas-sketch-cli sketch.js --new --open ``` -------------------------------- ### Convert Image Sequence to GIF Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/cli.md Converts a sequence of images in a directory to a GIF file with a specified frame rate. Ensure the FPS matches your sketch settings. ```bash canvas-sketch-gif tmp/ output.gif --fps=24 ``` -------------------------------- ### Run Sketch from Clipboard Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/installation.md Pipes the content of your clipboard into canvas-sketch to create and run a new sketch file. Useful for quickly testing code snippets. ```sh pbpaste | canvas-sketch foo.js --new ``` -------------------------------- ### Import Canvas Sketch with ES Modules Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/hello-world.md If you prefer ES Module syntax, you can use 'import' instead of 'require' to bring in the canvas-sketch library. ```javascript import canvasSketch from 'canvas-sketch'; ``` -------------------------------- ### Use Paper Size Presets Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/physical-units.md Configure print dimensions using convenient string presets like 'A4' or 'letter'. The 'units' setting still allows you to work in your preferred measurement system. ```javascript const settings = { // For print output pixelsPerInch: 300, // Results in 21 x 29.7 cm dimensions: 'A4', // You can still work in your preferred units units: 'in' }; ``` -------------------------------- ### Import canvas-sketch Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/api.md Import the default canvasSketch function using CommonJS or ES Modules. ```javascript const canvasSketch = require('canvas-sketch'); ``` ```javascript import canvasSketch from 'canvas-sketch'; ``` -------------------------------- ### Configure Sketch Dimensions Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/api.md Set the dimensions and units for your sketch, such as 11x7 inches. ```javascript const settings = { dimensions: [ 11, 7 ], units: 'in' }; ``` -------------------------------- ### Configure Physical Units for Print Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/physical-units.md Set custom dimensions, pixels per inch for print resolution, and specify units (e.g., 'in' for inches). This ensures artwork scales correctly for print. ```javascript const settings = { // Measurements of artwork dimensions: [ 3.5, 2 ], // Use a higher density for print resolution // (this defaults to 72, which is good for web) pixelsPerInch: 300, // All our units are inches units: 'in' } ``` -------------------------------- ### Importing canvas-sketch Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/api.md Shows how to import the canvasSketch function from the canvas-sketch library in both Node.js/CommonJS and ES Modules environments. ```APIDOC ## Importing canvas-sketch The default export is a function, `canvasSketch` which can be imported like so: ```js // Node.js/CommonJS const canvasSketch = require('canvas-sketch'); // ES Modules import canvasSketch from 'canvas-sketch'; ``` CommonJS is recommended for better compatibility with Node.js (i.e. for generating super-high resolution prints). ``` -------------------------------- ### canvasSketch Method Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/api.md Documentation for the main canvasSketch function, including its signature, parameters, and return value. ```APIDOC ## `promise = canvasSketch(sketch, [settings])` The library exports the default `canvasSketch` function, which takes in a `sketch` function and optional [`settings` object](#settings). The `sketch` function can be sync or async (i.e. returns a promise), and is expected to have a signature similar to: ```js // Sync + ES5 function sketch (initialProps) { // ... load & setup content return function (renderProps) { // ... render content }; } // Async + ES6 const sketch = async () => { await someLoader(); return ({ width, height }) => { // ... Render... }; } ``` See the [props](#props) for details about what is contained in the object passed to these functions. You can also return a [renderer object](#renderer-objects) for more advanced functionality, for example to react to canvas resize events. ```js const sketch = () => { return { render ({ frame }) { console.log('Rendering frame #%d', frame); }, resize ({ width, height }) { console.log('Canvas has resized to %d x %d', width, height); } }; } ``` The return value of `canvasSketch` is a promise, resolved to a [`SketchManager` instance](#sketchmanager). ``` -------------------------------- ### Exporting Multiple Layers (JSON and Images) Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/exporting-artwork.md Return an array of file descriptors to export multiple files, such as a JSON metadata file and one or more images. Each element in the array is exported as a separate layer. ```javascript canvasSketch(() => { return ({ canvas, width, height } => { // Render your scene... // ... // Export your file return [ // layer0 = JSON { data: JSON.stringify({ foo: 'bar' }), extension: '.json' }, // layer1 = i.e. PNG canvas, // layer2 = i.e. PNG { data: someOtherCanvas, suffix: '.thumb' }, ]; }); }); ``` -------------------------------- ### Renderer Object Structure Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/api.md An alternative to returning a render function, you can return an object with methods like `render`, `begin`, and `end` to control the rendering lifecycle. ```javascript const sketch = () => { return { render ({ frame }) { console.log('Rendering frame #%d', frame); }, begin () { // First frame of loop }, end () { // Last frame of loop } }; } ``` -------------------------------- ### Import Math and Random Utilities in JavaScript Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/other-topics.md Import specific math and randomness utilities from the canvas-sketch-util module. These utilities can be used independently of the main canvas-sketch framework. ```javascript const { lerp, clamp } = require('canvas-sketch-util/math'); // Randomness & noise utilities const { noise2D } = require('canvas-sketch-util/random'); ``` -------------------------------- ### Control Sketch Playback with SketchManager Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/api.md Use the SketchManager instance to control sketch playback. Attach event listeners to toggle play/pause functionality. ```javascript const start = async () => { const manager = await canvasSketch(sketch, settings); window.addEventListener('click', () => { if (manager.props.playing) manager.pause(); else manager.play(); }); }; ``` -------------------------------- ### Basic Sketch Function Structure Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/api.md The sketch function receives initial props and returns a render function. The same props object is passed to all functions for performance. ```javascript const sketch = (initialProps) => { return (renderProps) => { /* ... */ }; }; ``` -------------------------------- ### SketchManager Instance Properties Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/api.md These properties provide access to the current state and configuration of the sketch. ```APIDOC ## `SketchManager` Instance Properties ### Description Provides read-only access to the current state and configuration of the sketch. ### Properties - `manager.props`: A getter that returns the current properties of the sketch. - `manager.settings`: A getter that returns the settings applied to the sketch. - `manager.sketch`: A getter that returns the 'sketch' interface, which can be a renderer function or a renderer object. ``` -------------------------------- ### Return a Renderer Object Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/api.md Return a renderer object to handle render and resize events for advanced functionality. ```javascript const sketch = () => { return { render ({ frame }) { console.log('Rendering frame #%d', frame); }, resize ({ width, height }) { console.log('Canvas has resized to %d x %d', width, height); } }; } ``` -------------------------------- ### Exporting JPEG or WEBP with Quality Settings Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/exporting-artwork.md Use the 'encoding' and 'encodingQuality' settings to export lossy image formats like JPEG or WEBP. Specify the MIME type for encoding and a quality value between 0 and 1. ```javascript const settings = { dimensions: 'a4', encoding: 'image/jpeg', encodingQuality: 0.75, pixelsPerInch: 300, units: 'in' }; ``` -------------------------------- ### Set Output Folder with CANVAS_SKETCH_OUTPUT Environment Variable Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/exporting-artwork.md Alternatively, set the CANVAS_SKETCH_OUTPUT environment variable to define the output directory. This path can be absolute or relative and is overridden by the --output flag. ```sh CANVAS_SKETCH_OUTPUT=./outputs canvas-sketch src/index.js ``` -------------------------------- ### Stream Animations to GIF using FFMPEG Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/exporting-artwork.md To save animations as GIF files instead of MP4, specify the format using the --stream flag. ```sh canvas-sketch animation.js --output=tmp --stream=gif ``` -------------------------------- ### Direct glslify Usage Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/webgl.md An alternative method to inlining GLSL files using glslify directly with a file path. This is equivalent to requiring the file. ```javascript const path = require('path'); const glslify = require('glslify'); // this will get inlined into a string at bundle time const frag = glslify(path.resolve(__dirname, 'cool-shader.frag')); ``` -------------------------------- ### Utility Functions Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/api.md These functions can be called from within your sketch to control rendering, update state, and manage the animation loop. ```APIDOC ## Function Props - `render()`: Dispatches a re-draw, triggering your sketch's renderer. - `update(obj)`: Pass new settings (e.g., `{ width, height }`) to mutate the sketch's state. - `exportFrame(obj)`: Programmatically trigger a frame export. Can specify `{ commit: true }` to git commit before exporting, or `{ save: false }` to disable file saving and return a promise of exported layers. - `play()`: Play/resume the animation loop. - `pause()`: Pause the animation loop. - `stop()`: Stop the animation loop and return to frame zero. - `togglePlay()`: Toggles play/pause state of the animation loop. ``` -------------------------------- ### Customize File Naming Settings Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/exporting-artwork.md Modify the default file naming scheme by passing a 'settings' object with 'name', 'prefix', or 'suffix' properties. ```js const settings = { // The file name without extension, defaults to current time stamp name: 'foobar', // Optional prefix applied to the file name prefix: 'artwork', // Optional suffix applied to the file name suffix: '.draft' }; ``` -------------------------------- ### Specify Output Folder with --output Flag Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/exporting-artwork.md Use the --output flag with canvas-sketch-cli to specify a directory for exported files, relative to the current working directory. ```sh canvas-sketch src/index.js --output=media/ ``` -------------------------------- ### Exporting JSON File Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/exporting-artwork.md Return a file descriptor object with 'data' and 'extension' to export custom file types like JSON. The 'data' can be a string, ArrayBuffer, or Blob. ```javascript canvasSketch(() => { return ({ context, width, height } => { // Render your scene... // ... // Export your file return { data: JSON.stringify({ foo: 'bar' }), extension: '.json' }; }); }); ``` -------------------------------- ### Running canvas-sketch in Node.js with node-canvas Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/exporting-artwork.md Utilize the 'canvas' module in Node.js for rendering large prints that exceed browser limitations. Pass a Cairo-backed canvas instance to canvas-sketch settings and stream the output. ```javascript const canvasSketch = require('canvas-sketch'); const {createCanvas} = require('canvas'); // Create a new 'node-canvas' interface const canvas = createCanvas(); const settings = { // Pass in the Cairo-backed canvas canvas // Optionally set dimensions / units / etc // ... }; const sketch = () => { return ({ context }) => { // ... draw your artwork just like in the browser ... }; }; canvasSketch(sketch, settings) .then(() => { // Once sketch is loaded & rendered, stream a PNG with node-canvas const out = fs.createWriteStream('output.png'); const stream = canvas.createPNGStream(); stream.pipe(out); out.on('finish', () => console.log('Done rendering')); }); ``` -------------------------------- ### Convert Image Sequence to MP4 Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/cli.md Converts a sequence of images to an MP4 file, automatically generating a timestamped filename. Supports specifying frame rate and exact frame sequences. ```bash canvas-sketch-mp4 tmp/ --fps=24 ``` ```bash canvas-sketch-mp4 tmp/%02d.png ``` -------------------------------- ### Stream Animations to MP4 using FFMPEG Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/exporting-artwork.md Enable FFMPEG streaming for animations by using the --stream flag with canvas-sketch-cli. This saves animations directly to an MP4 file. ```sh canvas-sketch animation.js --output=tmp --stream ``` -------------------------------- ### Draw Artwork with Physical Units Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/physical-units.md Utilize the width and height properties (in specified units) within the renderer function to draw elements with precise physical dimensions. Includes a utility for drawing circles. ```javascript const settings = { // Measurements of artwork dimensions: [ 3.5, 2 ], // Use a higher density for print resolution // (this defaults to 72, which is good for web) pixelsPerInch: 300, // All our units are inches units: 'in' } const sketch = () => { // Utility to draw a circle const circle = (context, x, y, radius, fill) => { context.beginPath(); context.arc(x, y, radius, 0, Math.PI * 2, false); if (fill) context.fill(); context.stroke(); }; return ({ context, width, height }) => { // Here, the 'width' and 'height' are in inches // Fill the whole card with black context.fillStyle = '#000'; context.fillRect(0, 0, width, height); // Now draw some circles with alternating radii // between 0.5 and 0.25 inches context.strokeStyle = '#fff'; context.fillStyle = '#fff'; context.lineWidth = 0.01; for (let i = 0; i < 5; i++) { const x = i / 4 * width; const y = height / 2; const radius = i % 2 === 0 ? 0.5 : 0.25; const fill = i % 4 === 0; circle(context, x, y, radius, fill); } }; }; ``` -------------------------------- ### Define an Async Sketch Function Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/api.md An asynchronous sketch function that returns a rendering function after loading. ```javascript const sketch = async () => { await someLoader(); return ({ width, height }) => { // ... Render... }; } ``` -------------------------------- ### Enable Hot Reloading with CLI Flag Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/hot-reloading.md Use the `--hot` flag when running canvas-sketch from the command line to enable hot reloading. This improves the development feedback loop by applying code changes without a full page reload. ```sh canvas-sketch my-sketch.js --hot ``` -------------------------------- ### SketchManager Control Functions Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/api.md These functions allow direct control over the playback, rendering, and state of the sketch managed by SketchManager. ```APIDOC ## `SketchManager` Control Functions ### Description Provides methods to control the lifecycle and state of a canvas sketch. ### Functions - `manager.play()`: Starts or resumes sketch playback. - `manager.pause()`: Pauses sketch playback. - `manager.stop()`: Stops sketch playback. - `manager.render()`: Triggers a single re-render of the current frame. - `manager.exportFrame()`: Initiates the export of the current frame. - `manager.update(newSettings)`: Updates the sketch with new settings. Accepts an object of settings. - `manager.unload()`: Disposes of the current sketch and releases resources. - `manager.loadAndRun(sketch, settings)`: Unloads the current sketch and loads/runs a new one with the provided sketch function and settings. ``` -------------------------------- ### Update canvas-sketch JavaScript API Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/installation.md Re-install the canvas-sketch library locally in your project to update it. This command updates the dependency within your project's package.json. ```sh npm install canvas-sketch@latest ``` -------------------------------- ### Define a Sync Sketch Function Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/api.md A synchronous sketch function that returns another function for rendering. ```javascript function sketch (initialProps) { // ... load & setup content return function (renderProps) { // ... render content }; } ``` -------------------------------- ### Calculate Max Radius Using Trim Height Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/physical-units.md Calculate the maximum radius for elements within the trim area by subtracting padding from half of the `trimHeight`. This ensures elements stay within the safe zone. ```javascript const maxRadius = (trimHeight / 2) - (1 / 4); ``` -------------------------------- ### Props Available to Sketch Functions Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/api.md The `props` object is passed to your sketch function and contains various properties related to size, DOM elements, animation, and more. It is also passed to render and other utility functions. ```APIDOC ## Size Props - `units` (String): The working units, defaults to 'px'. - `width` (Number): The width of your artwork in working units. - `height` (Number): The height of your artwork in working units. - `canvasWidth` (Number): The current pixel width of the canvas. - `canvasHeight` (Number): The current pixel height of the canvas. - `styleWidth` (Number): The current CSS width of the canvas element. - `styleHeight` (Number): The current CSS height of the canvas element. - `scaleX` (Number): The current X scaling factor of the context. - `scaleY` (Number): The current Y scaling factor of the context. - `pixelRatio` (Number): The current pixel density being used. - `pixelsPerInch` (Number): Resolution used for physical measurements (e.g., inches) to pixels. ## DOM Props - `canvas` (): The canvas element currently being rendered into. - `context` (CanvasContext): The WebGL or 2D canvas context. ## Animation Props - `time` (Number): The current elapsed time of the loop in seconds. - `frame` (Number): The current elapsed frame index of the loop. - `playhead` (Number): The current playhead of the loop, between 0 and 1. - `deltaTime` (Number): The delta time in seconds since the last frame. - `playing` (Boolean): Whether the loop is currently playing. - `duration` (Number): The duration of the loop. - `totalFrames` (Number): The total number of frames in the loop. - `fps` (Number): The current frames per second. ## Misc Props - `exporting` (Boolean): True when rendering to a file or animation sequence. - `recording` (Boolean): True when rendering to an animation sequence. - `settings` (Object): A reference to the settings used to instantiate the sketch. ``` -------------------------------- ### Set Paper Orientation Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/physical-units.md Control the orientation of preset paper sizes (e.g., 'postcard') between 'landscape' and 'portrait'. This setting can also be applied to custom dimensions. ```javascript const settings = { dimensions: 'postcard', orientation: 'landscape' // also supports 'portrait' }; ``` -------------------------------- ### Manage State Outside Renderer Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/hello-world.md To ensure consistent rendering, define stateful values like random numbers outside the renderer function. This allows them to be initialized once and reused across renders. ```javascript // Good ! const sketch = () => { // Select an initial 0..1 random, outside your renderer const startXScale = Math.random(); return ({ width }) => { // Now scale to current width to get consistent rendering const startX = startXScale * width; context.fillRect(startX, 0, 50, 50); }; }; ``` -------------------------------- ### Manage Side Effects with `unload` Function Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/hot-reloading.md Implement the `unload` function within your sketch to clean up side effects like interval timers and event listeners. This prevents memory leaks and ensures a clean state when hot reloading. ```js const sketch = () => { const timer = setInterval(() => { console.log('Tick!'); }); const onClick = () => { console.log('Screen clicked!'); }; window.addEventListener('click', onClick); return { render ({ context, width, height, frame }) { // Render your content... }, unload () { // Dispose of side-effects clearInterval(timer); window.removeEventListener('click', onClick); } }; }; canvasSketch(sketch, { animate: true }); ``` -------------------------------- ### Assign Unique IDs to Multiple Sketches Source: https://github.com/mattdesl/canvas-sketch/blob/master/docs/hot-reloading.md When using multiple `canvasSketch()` calls in a single application, provide a unique `{ id }` for each sketch. This ensures that hot reloading is applied correctly to each individual sketch. ```js canvasSketch(mainSketch, { id: 'primary' }); canvasSketch(otherSketch, { id: 'secondary' }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.