Overview

The <canvas> element is a container for graphics drawn by JavaScript. Syntax:

<canvas id="myCanvas" width="200" height="100"></canvas>

Empty Canvas

<canvas id="myCanvas"width="200"height="100"style="border:1px solid #000000;">
</canvas>

A screenshot of an empty canvas

Line

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML canvas tag.</canvas>

<script>
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.moveTo(0,0);
    ctx.lineTo(200,100);
    ctx.stroke();
</script>

A screenshot of a canvas with a single line from the upper left to the lower right

Circle

<script>
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.beginPath();
    ctx.arc(95, 50, 40, 0, 2 * Math.PI);
    ctx.stroke();
</script>

A screenshot of a blank canvas with a dark circle in the middle of it

Text

<script>
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.font = "30px Arial";
    /* or strokeText: */
    ctx.fillText("Hello World", 10, 50);
</script>

A screenshot of a canvas with text that reads &lsquo;Hello world&rsquo;

Gradient

<script>
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");

    // Create gradient
    /* or createRadialGradient: */
    var grd = ctx.createLinearGradient(0, 0, 200, 0);
    grd.addColorStop(0, "red");
    grd.addColorStop(1, "white");

    // Fill with gradient
    ctx.fillStyle = grd;
    ctx.fillRect(10, 10, 150, 80);
</script>

A screenshot of a canvas with a red square that grades from dark to light from left to right