Code has been added to clipboard!

HTML canvas Tutorial

Reading time 2 min
Published Mar 19, 2019
Updated Oct 1, 2019

HTML canvas Tutorial: Main Tips

  • The <canvas> element provides a fixed-size drawing space, allowing developers to create HTML graphics. However, graphic creation with the <canvas> is usually done by using JavaScript.
  • The created canvas has a default size of 300px x 150px.
  • This HTML <canvas> tutorial lists the possibilities of using this element: combining multiple photos, drawing graphs, generating animations.

Use and Purpose of canvas

This HTML <canvas> tutorial explains that <canvas> HTML defines an area of the webpage that becomes a space for rendering HTML graphics. Alternative HTML graphics element is <svg>.

Remember: it is necessary to use the closing </canvas> tag.

In the example below, we set the drawing space:

Example
<canvas id="canvas01" width="400" height="300" style="border: 1px solid #eee;"></canvas>

Note: it is possible to manipulate the size of <canvas> by using HTML height and width attributes. They are the attributes this element accepts.

<canvas> in HTML allows developers to create rectangles. Different shapes have to be generated by adding together one or multiple paths. This HTML <canvas> tutorial explains how to draw rectangles with three functions:

  • fillRect(x, y, width, height) - creates a filled rectangle.
  • strokeRect(x, y, width, height) - creates a rectangular outline.
  • clearRect(x, y, width, height) - makes the rectangular transparent.

All three functions accept the same parameters. x and y indicate the position on the canvas of the top-left corner of the rectangle.

In this HTML <canvas> example, we create a filled rectangle:

Example
<script>
function draw() {
  var canvas = document.getElementById('canvas');
  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');

    ctx.fillRect(30, 30, 100, 100);
  }
}
</script>

The following HTML <canvas> example shows how to create a rectangular outline:

Example
<script>
function draw() {
  var canvas = document.getElementById('canvas');
  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');

    ctx.fillRect(30, 30, 100, 100);
    ctx.clearRect(45, 45, 60, 60);
    ctx.strokeRect(50, 50, 50, 50);

  }
}
</script>

Attributes for canvas

width

The width attribute sets width in pixels for a canvas element. Default is 300 pixels.

Example
<canvas id="canvas02" width="400" style="border: 1px solid #eee;"></canvas>

height

The height sets height in pixels for a canvas element. Default is 150 pixels.

Example
<canvas id="canvas03" height="300" style="border: 1px solid #eee;"></canvas>

Browser support

Chrome
1+
Edge
All
Firefox
1.5+
IE
9+
Opera
9+
Safari
2+

Mobile browser support

Chrome
18+
Firefox
4+
Opera
-
Safari
1+