Canvas

Generative Sketches

abstract01js

Julia Set

Zoomable Julia Set

Heightmap

Heightmap

Parallel Coordinates - Nutrition

Nutrition Parallel Coordinates

Map Projection Transitions

Map Projection Transitions

Basic Usage

<canvas id="tutorial" width="150" height="150"></canvas>

<script>
  var canvas = document.getElementById('tutorial');
  var ctx = canvas.getContext('2d');

  // your code here
</script>

Full Screen

<canvas id="tutorial" width="150" height="150"></canvas>

<script>
  var canvas = document.getElementById('tutorial');
  var ctx = canvas.getContext('2d');
  canvas.width = document.body.clientWidth;
  canvas.height = document.body.clientHeight;

  // your code here
</script>

Animation

See this blog post on smart animating with Canvas.

function render() {
  // your code here
};

window.requestAnimFrame = window.requestAnimationFrame  || 
              window.webkitRequestAnimationFrame        || 
              window.mozRequestAnimationFrame           || 
              window.oRequestAnimationFrame             || 
              window.msRequestAnimationFrame            || 
              function(callback, element) {
                window.setTimeout(callback, 16);
              };

(function animloop(){
  requestAnimFrame(animloop);
  render();
})();

Here's an example of a basic full screen, animated canvas.

Canvas Scratch Pad

Canvas Scratch Pad

Clear Canvas

// clear the canvas
ctx.fillStyle = "#fff"
ctx.fillRect(0,0,width,height);

Gradient

Canvas also has methods for linear and radial gradients.

// horizontal hue gradient
for (var i = 0; i < width; i++) {
  ctx.fillStyle = "hsl(" + i + ",50%,50%)";
  ctx.fillRect(i,0,1,height);
}

Double Gradient

// horizontal hue, vertical saturation gradient
for (var i = 0; i < 360; i++) {
  for (var j = 0; j < 400; j++) {
    ctx.fillStyle = "hsl(" + i + "," +
      Math.round(100*j/400) + "%,50%)";
    ctx.fillRect(i,j,1,1);
  }
}

Circular Motion

Use this example in animate mode:

// circular motion
var time = Date.now() / 1600;
var x = Math.sin(time);
var y = Math.cos(time);

// fade canvas
ctx.fillStyle = "rgba(0,0,0,0.2)"
ctx.fillRect(0,0,width,height);

// scale and center
var i = width * ((1+x)/2);
var j = height * ((1+y)/2);

// draw dot
ctx.fillStyle = "#fff";
ctx.fillRect(i,j,2.5,2.5);

Canvas Cheat Sheet

Nihilogic's Canvas Cheat Sheet

Coordinate Transformations

See this tutorial for examples of translating, rotating and scaling the canvas.

Coordinate Transform Example

Compositing

globalCompositeOperation examples

Resources

Galleries

Books

SVG

WebGL

Color

Named and Brewer Colors in Chromas.js

Compatibity

d3.js

d3.js Gallery

Three.js

Three.js Gallery

Processing.js

Processing.js