margarettrias.org

HTML5 Canvas

July 8, 2011

The HTML5 Canvas element is used to draw graphics using Javascript. The most useful tutorial I have found for learning about HTML5 Canvas is this:

Dive Into HTML5

Here are some results of my explorations with Canvas, learning Javascript along the way ...

Basic Elements

Create a canvas in the body of your html document like so:

<canvas id="MyFirstCanvas" width="400" height="400"></canvas>

To display the canvas upon loading your document, you could use the following javascript:

<script>
window.onload = function draw() {
  try {
    var canvas_1 = document.getElementById("MyFirstCanvas");
    var ctx_1 = canvas_1.getContext("2d");
    someFunction(ctx_1);
 
    var canvas_2 = document.getElementById("MySecondCanvas");
    var ctx_2 = canvas_2.getContext("2d");
    anotherFunction(ctx_2);
 
  } catch(err) {}
}
</script>

Gradients

I used a somewhat arbitrary mathematical function to generate a 2D color gradient.

Lots of dots!

Mathematical Functions

Sine(x)

A very twisty spiral

Last modified: