canvas-sketch
[beta] A framework for making generative artwork in JavaScript and the browser.
Top Related Projects
p5.js is a client-side JS platform that empowers artists, designers, students, and anyone to learn to code and express themselves creatively on the web. It is based on the core principles of Processing. http://twitter.com/p5xjs —
Javascript Canvas Library, SVG-to-Canvas (& canvas-to-SVG) Parser
The HTML5 Creation Engine: Create beautiful digital content with the fastest, most flexible 2D WebGL renderer.
The Swiss Army Knife of Vector Graphics Scripting – Scriptographer ported to JavaScript and the browser, using HTML5 Canvas. Created by @lehni & @puckey
Konva.js is an HTML5 Canvas JavaScript framework that extends the 2d context by enabling canvas interactivity for desktop and mobile applications.
The Easel Javascript library provides a full, hierarchical display list, a core interaction model, and helper classes to make working with the HTML5 Canvas element much easier.
Quick Overview
Canvas-sketch is a JavaScript framework designed for creating generative art and creative coding projects. It provides a structured environment for working with HTML5 canvas, WebGL, and other creative coding tools, focusing on exporting high-quality artwork and animations.
Pros
- Streamlines the process of setting up and managing creative coding projects
- Offers easy export options for high-resolution images and animations
- Provides a CLI tool for quick project scaffolding and development
- Supports various rendering contexts, including 2D canvas, WebGL, and SVG
Cons
- Learning curve for developers new to generative art or creative coding
- Limited documentation for advanced features and techniques
- May be overkill for simple canvas projects or quick prototypes
- Dependency on Node.js for full functionality, which might not suit all workflows
Code Examples
Basic sketch setup:
const canvasSketch = require('canvas-sketch');
const settings = {
dimensions: [2048, 2048]
};
const sketch = () => {
return ({ context, width, height }) => {
context.fillStyle = 'black';
context.fillRect(0, 0, width, height);
context.fillStyle = 'white';
context.beginPath();
context.arc(width / 2, height / 2, 300, 0, Math.PI * 2);
context.fill();
};
};
canvasSketch(sketch, settings);
Using random number generation:
const canvasSketch = require('canvas-sketch');
const random = require('canvas-sketch-util/random');
const settings = {
dimensions: [2048, 2048]
};
const sketch = () => {
return ({ context, width, height }) => {
context.fillStyle = 'black';
context.fillRect(0, 0, width, height);
for (let i = 0; i < 100; i++) {
const x = random.range(0, width);
const y = random.range(0, height);
const radius = random.range(5, 20);
context.beginPath();
context.arc(x, y, radius, 0, Math.PI * 2);
context.fillStyle = `hsl(${random.range(0, 360)}, 50%, 50%)`;
context.fill();
}
};
};
canvasSketch(sketch, settings);
Exporting an animation:
const canvasSketch = require('canvas-sketch');
const settings = {
dimensions: [512, 512],
animate: true,
duration: 4,
fps: 30
};
const sketch = () => {
return ({ context, width, height, playhead }) => {
context.fillStyle = 'black';
context.fillRect(0, 0, width, height);
const x = Math.sin(playhead * Math.PI * 2) * width / 4 + width / 2;
const y = Math.cos(playhead * Math.PI * 2) * height / 4 + height / 2;
context.beginPath();
context.arc(x, y, 50, 0, Math.PI * 2);
context.fillStyle = 'white';
context.fill();
};
};
canvasSketch(sketch, settings);
Getting Started
-
Install canvas-sketch globally:
npm install canvas-sketch-cli -g
-
Create a new sketch:
canvas-sketch sketch.js --new
-
Run the sketch:
canvas-sketch sketch.js
This will open your default browser with the sketch running. Edit the sketch.js
file to modify your artwork, and the browser will automatically reload to reflect your changes.
Competitor Comparisons
p5.js is a client-side JS platform that empowers artists, designers, students, and anyone to learn to code and express themselves creatively on the web. It is based on the core principles of Processing. http://twitter.com/p5xjs —
Pros of p5.js
- Larger community and more extensive documentation
- Easier for beginners with a simpler API and built-in functions
- Cross-platform compatibility (web, mobile, desktop)
Cons of p5.js
- Less flexible for advanced users or specific use cases
- Heavier library size, which may impact performance
- Limited control over the rendering context and setup
Code Comparison
p5.js:
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
ellipse(50, 50, 80, 80);
}
canvas-sketch:
const canvasSketch = require('canvas-sketch');
const settings = {
dimensions: [ 400, 400 ]
};
const sketch = () => {
return ({ context, width, height }) => {
context.fillStyle = 'rgb(220, 220, 220)';
context.fillRect(0, 0, width, height);
context.beginPath();
context.arc(50, 50, 40, 0, Math.PI * 2);
context.fill();
};
};
canvasSketch(sketch, settings);
This comparison highlights the simplicity of p5.js for basic sketches, while canvas-sketch offers more control over the rendering process and setup. p5.js abstracts many low-level operations, making it easier for beginners, whereas canvas-sketch provides a more flexible environment for advanced users who need finer control over their sketches.
Javascript Canvas Library, SVG-to-Canvas (& canvas-to-SVG) Parser
Pros of Fabric.js
- Robust object model with built-in support for shapes, images, and text
- Extensive event handling system for interactive canvas elements
- Serialization and deserialization of canvas objects to JSON
Cons of Fabric.js
- Steeper learning curve due to its comprehensive feature set
- Larger file size, which may impact load times for simpler projects
- Less focus on generative art and algorithmic drawing techniques
Code Comparison
Canvas-sketch:
const canvasSketch = require('canvas-sketch');
const settings = {
dimensions: [ 2048, 2048 ]
};
const sketch = () => {
return ({ context, width, height }) => {
context.fillStyle = 'black';
context.fillRect(0, 0, width, height);
};
};
canvasSketch(sketch, settings);
Fabric.js:
var canvas = new fabric.Canvas('canvas');
var rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'red',
width: 20,
height: 20
});
canvas.add(rect);
Canvas-sketch focuses on creating generative art and provides a simple API for setting up canvas contexts, while Fabric.js offers a more object-oriented approach with built-in shapes and interactive elements. Canvas-sketch is better suited for algorithmic drawing, while Fabric.js excels in creating interactive canvas applications with manipulable objects.
The HTML5 Creation Engine: Create beautiful digital content with the fastest, most flexible 2D WebGL renderer.
Pros of PixiJS
- Powerful rendering engine with WebGL support, offering better performance for complex graphics and animations
- Extensive set of built-in features for game development, including sprite management and scene graphs
- Large and active community with numerous plugins and extensions available
Cons of PixiJS
- Steeper learning curve, especially for developers new to game development or advanced graphics programming
- Heavier library size, which may impact initial load times for web applications
- More opinionated structure, which can be limiting for certain types of creative coding projects
Code Comparison
canvas-sketch:
const canvasSketch = require('canvas-sketch');
const settings = {
dimensions: [2048, 2048]
};
const sketch = () => {
return ({ context, width, height }) => {
context.fillStyle = 'black';
context.fillRect(0, 0, width, height);
};
};
canvasSketch(sketch, settings);
PixiJS:
const app = new PIXI.Application({ width: 2048, height: 2048 });
document.body.appendChild(app.view);
const graphics = new PIXI.Graphics();
graphics.beginFill(0x000000);
graphics.drawRect(0, 0, app.screen.width, app.screen.height);
app.stage.addChild(graphics);
Both libraries provide ways to create and manipulate graphics, but PixiJS offers a more structured approach with its Application and stage concepts, while canvas-sketch focuses on a simpler, function-based setup for creative coding.
The Swiss Army Knife of Vector Graphics Scripting – Scriptographer ported to JavaScript and the browser, using HTML5 Canvas. Created by @lehni & @puckey
Pros of Paper.js
- Comprehensive vector graphics library with a rich set of features
- Object-oriented approach with a Scene Graph for easier manipulation of shapes
- Extensive documentation and examples for easier learning
Cons of Paper.js
- Steeper learning curve due to its more complex architecture
- Larger file size, which may impact load times for web applications
- Less flexibility for custom rendering techniques or non-standard workflows
Code Comparison
Paper.js:
paper.setup('myCanvas');
var circle = new Path.Circle({
center: view.center,
radius: 50,
fillColor: 'red'
});
Canvas-sketch:
const canvasSketch = require('canvas-sketch');
const settings = {
dimensions: [800, 600]
};
const sketch = () => {
return ({ context, width, height }) => {
context.fillStyle = 'red';
context.beginPath();
context.arc(width / 2, height / 2, 50, 0, Math.PI * 2);
context.fill();
};
};
canvasSketch(sketch, settings);
Canvas-sketch provides a more lightweight and flexible approach, focusing on creative coding and generative art. It offers easier integration with other libraries and custom rendering techniques. Paper.js, on the other hand, provides a more structured and comprehensive solution for vector graphics manipulation, making it suitable for complex illustrations and interactive graphics applications.
Konva.js is an HTML5 Canvas JavaScript framework that extends the 2d context by enabling canvas interactivity for desktop and mobile applications.
Pros of Konva
- Comprehensive framework for creating complex canvas applications with built-in support for shapes, layers, and animations
- Extensive documentation and active community support
- Touch and mobile device support out of the box
Cons of Konva
- Larger file size and potential performance overhead for simpler projects
- Less flexibility for custom rendering techniques compared to lower-level canvas manipulation
- Steeper learning curve for developers familiar with raw canvas API
Code Comparison
Konva:
const stage = new Konva.Stage({
container: 'container',
width: 400,
height: 400
});
const layer = new Konva.Layer();
const circle = new Konva.Circle({
x: 200, y: 200, radius: 50, fill: 'red'
});
layer.add(circle);
stage.add(layer);
Canvas-sketch:
const canvasSketch = require('canvas-sketch');
const settings = {
dimensions: [400, 400]
};
const sketch = () => {
return ({ context, width, height }) => {
context.fillStyle = 'red';
context.beginPath();
context.arc(200, 200, 50, 0, Math.PI * 2);
context.fill();
};
};
canvasSketch(sketch, settings);
The Easel Javascript library provides a full, hierarchical display list, a core interaction model, and helper classes to make working with the HTML5 Canvas element much easier.
Pros of EaselJS
- Comprehensive library with a rich set of features for creating interactive graphics and animations
- Well-established ecosystem with extensive documentation and community support
- Provides a display list for easy management of visual elements
Cons of EaselJS
- Larger file size and potentially heavier performance impact
- Steeper learning curve due to its extensive API and object-oriented approach
- Less focused on modern JavaScript practices and modular development
Code Comparison
EaselJS:
var stage = new createjs.Stage("canvas");
var circle = new createjs.Shape();
circle.graphics.beginFill("red").drawCircle(0, 0, 50);
stage.addChild(circle);
createjs.Ticker.addEventListener("tick", stage);
canvas-sketch:
const canvasSketch = require('canvas-sketch');
const settings = {
dimensions: [800, 600]
};
const sketch = () => {
return ({ context, width, height }) => {
context.fillStyle = 'red';
context.beginPath();
context.arc(width / 2, height / 2, 50, 0, Math.PI * 2);
context.fill();
};
};
canvasSketch(sketch, settings);
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
canvas-sketch
canvas-sketch
is a loose collection of tools, modules and resources for creating generative art in JavaScript and the browser.
-
:closed_book: Documentation
-
:wrench: Examples
example of canvas-sketch
running in Chrome
â
Quick Start with Node.js & npm
To jump directly into canvas-sketch
, try the following terminal commands with node@15.x
and npm@7.x
or newer:
# Make a new folder to hold all your generative sketches
mkdir my-sketches
# Move into that folder
cd my-sketches
# Scaffold a new 'sketch.js' file and open the browser
npx canvas-sketch-cli sketch.js --new --open
:bulb: Notice the
x
innpx
, and the-cli
incanvas-sketch-cli
Now, while in the browser, hit Cmd + S
or Ctrl + S
to export a high-resolution PNG of your artwork to your ~/Downloads
folder.
More Commands
Some other commands to try:
# Start the tool on an existing file and change PNG export folder
npx canvas-sketch-cli src/foobar.js --output=./tmp/
# Start a new sketch from the Three.js template
npx canvas-sketch-cli --new --template=three --open
# Build your sketch to a sharable HTML + JS website
npx canvas-sketch-cli src/foobar.js --build
# Develop with "Hot Reloading" instead of full page reload
npx canvas-sketch-cli src/foobar.js --hot
For more features and details, see the Documentation.
Installation Guide
The examples above use npx
which is a convenient way to install and run a local CLI tool, but you might want to setup canvas-sketch
as a global command. You can see more details in the Installation Guide.
Code Example
Once you have the CLI tool running, you can try this example of an A4 print artwork.
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);
When exporting the image in browser with Cmd + S
or Ctrl + S
keystrokes, the saved PNG file matches 21 x 29.7 cm at 300 DPI, and can be printed with archival ink on quality paper.
Resulting image looks something like this:
Note: The above PNG file has been scaled/optimized for web.
Roadmap
There are many features still outstanding, such as:
- API & CLI Docs
- Easy & beginner-friendly examples
- Website/frontend
- HUD/GUI controls
- "Gallery Mode" for viewing many local sketches
- External Module for utilities (randomness, geometry, etc)
- Unit tests
- More??
License
MIT, see LICENSE.md for details.
Top Related Projects
p5.js is a client-side JS platform that empowers artists, designers, students, and anyone to learn to code and express themselves creatively on the web. It is based on the core principles of Processing. http://twitter.com/p5xjs —
Javascript Canvas Library, SVG-to-Canvas (& canvas-to-SVG) Parser
The HTML5 Creation Engine: Create beautiful digital content with the fastest, most flexible 2D WebGL renderer.
The Swiss Army Knife of Vector Graphics Scripting – Scriptographer ported to JavaScript and the browser, using HTML5 Canvas. Created by @lehni & @puckey
Konva.js is an HTML5 Canvas JavaScript framework that extends the 2d context by enabling canvas interactivity for desktop and mobile applications.
The Easel Javascript library provides a full, hierarchical display list, a core interaction model, and helper classes to make working with the HTML5 Canvas element much easier.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot