Intro

This tutorial describes how to use the canvas element to draw 2D graphics starting with the basics. The provided examples should give you some clear ideas about what you can do with canvas and will provide code snippets that may get you started in building your own content.

Using the canvas element is not very difficult but you do need a basic understanding of HTML and JavaScript. The canvas element is not supported in some older browsers but is supported in recent versions of all major browsers. The default size of the canvas is 300 px × 150 px (width × height). But custom sizes can be defined using the CSS height and width property. To draw graphics on the canvas, we use a JavaScript context object which creates graphics on the fly.

Usage

The canvas element has only two attributes: width and height.The id attribute isn't specific to the canvas element but is one of the global HTML attributes which can be applied to any HTML element (like class for instance).

Let's see how the canvas looks like in html.

<canvas id="tutorial" width="150" height="150"></canvas>

getContext()

The canvas is initially blank. To display something, first of all, a script needs to access the rendering context and draw on it. The canvas element has a method called getContext(), used to obtain the rendering context and its drawing functions. getContext() takes one parameter: the type of context. For 2D graphics, such as those covered by this tutorial, you specify "2d" to get a CanvasRenderingContext2D.

let canvas = document.getElementById('tutorial');
let ctx = canvas.getContext('2d');

Drawing Rectangles

The ctx.fillRect() method of the Canvas 2D API draws a filled rectangle at (x, y) position whose size is determined by width and height and whose style is determined by the fillStyle attribute.

Syntax

void ctx.fillRect(x, y, width, height);

Let's see a simple example.

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
    <style type="text/css">
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body onload="paint()">
    <script type="text/javascript">
      function paint() {
        let canvas = document.getElementById('tutorial');
        let ctx = canvas.getContext('2d');
        ctx.fillStyle = "green";
        ctx.fillRect(10, 10, 100, 100);
      }
    </script>
    <canvas id="tutorial" width="250" height="250"></canvas>
  </body>
</html>

Here is some functions about drawing rectangles.

FunctionDescription
strokeRect(x, y, width, height)Draws a rectangular outline.
clearRect(x, y, width, height)Clears the specified rectangular area, making it fully transparent.

Drawing Paths

The other primitive shapes are paths. A path is a list of points, connected by segments of lines that can be of different shapes, curved or not curved, of different width and different color.

The first step is to begin drawing.

beginPath()

Creates a new path. Once created, future drawing commands are directed into the path and used to build the path up.

moveTo()

The method of the Canvas 2D API moves the starting point of a new sub-path to the (x, y) coordinates.

Syntax

void ctx.moveTo(x, y);

lineTo()

The method of the Canvas 2D API connects the last point in the sub-path to the x, y coordinates with a straight line (but does not actually draw it).

syntax

void ctx.lineTo(x, y);

Let's see a simple example.

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
    <style type="text/css">
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body onload="paint()">
    <script type="text/javascript">
      function paint() {
        let canvas = document.getElementById("canvas");
        let ctx = canvas.getContext("2d");
        ctx.beginPath();
        ctx.moveTo(0, 0);
        ctx.lineTo(250, 250);
        ctx.stroke();
      }
    </script>
    <canvas id="canvas" width="250" height="250"></canvas>
  </body>
</html>

Here is some functions drawing paths.

FunctionDescription
closePath()Closes the path so that future drawing commands are once again directed to the context.
stroke()Draws the shape by stroking its outline.
fill()Draws a solid shape by filling the paths content area.

Drawing Arcs

We use the arc() or arcTo() methods in order to draw arcs or circles.

arc()

The method of the Canvas 2D API adds an arc to the path which is centered at (x, y) position with radius r starting at startAngle and ending at endAngle going in the given direction by anticlockwise (defaulting to clockwise).

Syntax

void ctx.arc (x, y, radius, startAngle, endAngle, anticlockwise);

Let's see an example.

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
    <style type="text/css">
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body onload="paint()">
    <script type="text/javascript">
      function paint() {
        let canvas = document.getElementById("canvas");
        let ctx = canvas.getContext("2d");
        ctx.beginPath();
        ctx.arc(100, 75, 50, 0, 2 * Math.PI);
        ctx.stroke();
      }
    </script>
    <canvas id="canvas" width="250" height="250"></canvas>
  </body>
</html>

Drawing Texts

Now it's time to talk a little about drawing texts.

fillText()

The method of the Canvas 2D API fills a given text at the given (x, y) position. If the optional fourth parameter for a maximum width is provided the text will be scaled to fit that width.

Syntax

void ctx.fillText(text, x, y [, maxWidth]);

Let's see an example.

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
    <style type="text/css">
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body onload="paint()">
    <script type="text/javascript">
      function paint() {
        let canvas = document.getElementById("canvas");
        let ctx = canvas.getContext("2d");
        ctx.font = "40px serif";
        ctx.fillText("Hello W3docs", 10, 100);
      }
    </script>
    <canvas id="canvas" width="250" height="250"></canvas>
  </body>
</html>

There is another function to draw text with javascript canvas.StrokeText function draws stroke style text. Here is its syntax.

strokeText(text, x, y [, maxWidth])

Drawing Images

Until now we have created our shapes and applied styles to them. One of the more exciting features of canvas is the ability to use images. These can be used to do dynamic photo composting or as backdrops of graphs, for sprites in games, and so forth. External images can be used in any format supported by the browser such as PNG, GIF, or JPEG. You can even use the image produced by other canvas elements on the same page as the source!

DrawImage()

The method of the Canvas 2D API provides different ways to draw an image onto the canvas.

Syntax

void ctx.drawImage(image, dx, dy);
void ctx.drawImage(image, dx, dy, dWidth, dHeight);
void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

Let's make an example.

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
    <style type="text/css">
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body onload="paint()">
    <script type="text/javascript">
      function paint() {
        let canvas = document.getElementById("canvas");
        let ctx = canvas.getContext("2d");
        let img = new Image();
        img.onload = function() {
          ctx.drawImage(img, 0, 0);
        };
        img.src = 'http://www.w3docs.com/uploads/media/book_gallery/0001/01/066705b46be05dfdde77a1bc60c120b76257b553.png';
      }
    </script>
    <canvas id="canvas" width="250" height="250"></canvas>
  </body>
</html>

We can talk more and more about canvas, its methods and something else. There are many things connected with canvas and here is a list of that.

  • Transformations // save(), restore(), rotate(angle), translate(x, y), scale(x, y) etc... methods
  • Animations // with setInterval(), setTimeout(), requestAnimationFrame() etc...
  • Pixel manipulation // useing createImageData(), getImageData(), putImageData() etc...
  • etc...

Practice Your Knowledge

What can you do with the Canvas element in JavaScript according to the content found on w3docs.com?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?