### 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 =