Learn Canvas in 10 Minutes

By Xah Lee. Date: . Last updated: .

Here's a simple canvas.

We paint a line, arc, text and rectangle.

Here's the HTML:

<canvas id="c89344" width="100" height="100"></canvas>

Here's the CSS, we just added a border:

canvas#c89344 {border:solid thin gray}

Here's the JavaScript:

{

const ff = (() => {

    const yy = document.getElementById("canvas47541");

    // create drawing area
    const xx = yy.getContext("2d");

    // paint a line
    xx.beginPath();
    xx.strokeStyle = "red"; // specify color
    xx.moveTo(0,0); // move pen to
    xx.lineTo(50,50); // draw line to here
    xx.stroke(); // actually draw it

    // paint a arc
    xx.beginPath();
    xx.strokeStyle = "blue";
    xx.arc(50,50, 30, 0, 2 * Math.PI, true); // x, y, radius, angle 1, angle 2, counter-clockwise
    xx.stroke();

    // paint a text
    xx.fillText("canvas", 0, 90,);

    // paint a rectangle
    xx.fillStyle = "cyan"; // specify color
    xx.fillRect(50, 25, 15, 10); // x, y, width, height

});

ff();

}

How to Script Canvas

To script HTML canvas, you create a canvas element, set a context (getContext("2d")), then use various drawing or style commands to paint the canvas area. That's about it.

Note that all canvas technology provides is a pixel painting area with JavaScript commands to paint it. It is not aware of what you drew. You can think of it as painting on a wall. For example, if you draw a circle, and you want to delete it, you have to draw on top to “cover” it. If you want to move the circle, you have to draw something to “cover” it, then draw another one at the place you want. If you want to detect clicks on the circle, you have to find the click's coordinate, then manually compute whether that coordinate is within the circle.

Canvas is in contrast with SVG. With SVG, every element you create is a object, and can be manipulated, move to front/back, change parameters, or be animated, put “onclick” event on it, and any changes are rendered in real-time. [see Canvas vs SVG]

Now, all you need to know about scripting canvas is the list of drawing commands.

You should know the basics of JavaScript.

[see JavaScript Basics]

HTML Canvas Reference

HTML Canvas Reference

Canvas Topic

  1. Canvas vs SVG
  2. Learn Canvas in 10 Minutes
  3. Canvas Tutorial: Halma Board Game
  4. HTML Canvas Demo: Raycaster
  5. HTML Canvas Reference
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Patreon me $5. Ask me question on patreon