In this tutorial I’ll demonstrate the basics of the HTML5 canvas element.

Let’s begin by adding a canvas element:

<!doctype html>
<html>
  <head></head>

  <body>
    <!--Canvas-->
    <canvas id="canvas"></canvas>
  </body>
</html>

By default the canvas element has width/height of 300 pixels x 150 pixels (the gap above is a canvas).

Add a border to see it:

<canvas id="canvas" style="border:2px solid blue;"></canvas>


Add a fallback for older browsers by placing content inside the canvas element.

<canvas id="canvas" style="border:2px solid blue;">
  <h1>Update your web browser!</h1>
</canvas>


Drawing on the canvas requires a 2d render context:

<!doctype html>
<html>
  <head></head>

  <body>
    <script>
      // Use this 2d context for drawing
      var ctx = document.getElementById("canvas").getContext("2d"); 
    </script>

    <canvas id="canvas">
      <h1>Update your web browser!</h1>
    </canvas>
  </body>
</html>

This context object has methods we can use for drawing such as fillRect(x, y, width, height)

<script>
  var ctx = document.getElementById("canvas").getContext("2d"); 
  ctx.fillRect(0,0, 50, 50);
</script>

Change the fill color with fillStyle

<script>
  var ctx = document.getElementById("canvas").getContext("2d"); 
  ctx.fillStyle = "#A7E1BE"
  ctx.fillRect(0,0, 50, 50);
</script>

Or draw a rectangular outline with strokeRect(x, y, width, height)

<script>
  var ctx = document.getElementById("canvas").getContext("2d"); 
  ctx.strokeStyle = "#00ADE5"
  ctx.strokeRect(0,0, 50, 50);
</script>


For more complex shapes we use paths:

<script>
  var ctx = document.getElementById("canvas").getContext("2d"); 
  ctx.beginPath();
  ctx.moveTo(0,0);
  ctx.lineTo(50, 50);
  ctx.stroke();
</script>

beginPath(); Prepare the context for drawing paths

moveTo(x, y) Place the “pencil” at this point

lineTo(x, y) Creates a line to this point but doesn’t draw it

stroke() Strokes the path

Adding another lineTo will create a new line starting from where the last lineTo left off

<script>
  var ctx = document.getElementById("canvas").getContext("2d"); 
  ctx.beginPath();
  ctx.moveTo(0,0);
  ctx.lineTo(50, 50);
  ctx.lineTo(0, 50);
  ctx.stroke();
</script>

Replacing stroke with fill:

<script>
  var ctx = document.getElementById("canvas").getContext("2d"); 
  ctx.beginPath();
  ctx.moveTo(0,0);
  ctx.lineTo(50, 50);
  ctx.lineTo(0, 50);
  ctx.fill();
</script>

More shapes can be demonstrated here


Adding text inside the canvas is also possible:

<script>
  var ctx = document.getElementById("canvas").getContext("2d"); 
  ctx9.font = "48px sans-serif"
  ctx.fillText("text", 50, 50);
</script>


The 2d context has many more methods such as rendering images or gradients. For more I recommend continuing here.

Thanks for reading!