🚨 Time is Running Out: Reserve Your Spot in the Lucky Draw & Claim Rewards! START NOW

Code has been added to clipboard!

A Complete Illustrated HTML5 Canvas Tutorial

Reading time 3 min
Published Jun 23, 2017
Updated Jan 21, 2020

TL;DR – HTML canvas provides a drawing space of a fixed size in which you can draw using JavaScript.

What's HTML5 Canvas?

The <canvas> element was created by Apple in 2004, and added to the HTML5 specification later. It is a little bit more complex than basic elements, but widely used due to its flexibility. You can use HTML5 canvas for animations, game graphics, and other visual elements.

The HTML5 <canvas> element creates an area for drawing in 2D. It is 300 by 150 pixels in size by default, but you can change the size using height and width attributes.

You can also use CSS to modify the canvas itself – e.g., add a border:

Example
<!DOCTYPE html>
<html>
<body>
  <canvas id="ThisIsCanvas" width="150" height="150" style="border: 2px solid #000000;">
    HTML5 canvas tag is unsupported in your browser.
  </canvas>
</body>
</html>

You can also see some text within the tags in the example above. It is called the fallback content: the browser will display it if the <canvas> element cannot be loaded. It does not need to be a text necessarily: you may add an image as well.

Note: we recommend using the id attribute to simplify accessing the canvas.

Working with Canvas

You need to access the area with JavaScript to actually draw in it. To understand the necessary steps, we'll analyze a simple canvas drawing and its script.

For our simple HTML5 canvas tutorial, we'll use the example below. In it, we draw a square filled with solid color:

Example
<!DOCTYPE html>
<html>
<body>
  <canvas id="ThisIsCanvas" width="150" height="150" style="border: 2px solid #000000;">
    HTML5 canvas tag is unsupported in your browser.
  </canvas>
<script>
  var b=document.getElementById("ThisIsCanvas"); 
  var ctx=b.getContext("2d"); 
  ctx.fillStyle="#E9967A"; 
  ctx.fillRect(0, 0, 150, 150); 
</script> 
</body>
</html>

Now let's explain the JS script line by line:

var b = document.getElementById("ThisIsCanvas"); We define the canvas element
var ctx = b.getContext("2d"); We define the context
ctx.fillStyle = "#E9967A";
ctx.fillRect(0, 0, 150, 150);
We draw a shape (a rectangle) and color it using the color we chose

See the functions you can use to draw rectangles:

  • fillRect(x, y, width, height) creates a filled rectangle
  • fillStyle(color or pattern) defines a style for filling the rectangle
  • strokeRect(x, y, width, height) creates a rectangle using strokes or borders
  • strokeStyle(color or pattern) defines a stroke style for the rectangle
  • clearRect(x, y, width, height) clears the specified space in the rectangle

Note: x and y represent the distance from the x and y axes of the HTML5 canvas.

DataCamp
Pros
  • Easy to use with a learn-by-doing approach
  • Offers quality content
  • Gamified in-browser coding experience
  • The price matches the quality
  • Suitable for learners ranging from beginner to advanced
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable
Udacity
Pros
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
Main Features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid Certificates of completion
Udemy
Pros
  • Easy to navigate
  • No technical issues
  • Seems to care about its users
Main Features
  • Huge variety of courses
  • 30-day refund policy
  • Free certificates of completion

HTML5 Canvas Examples

Now that you're familiar with the HTML5 canvas, let's see more examples and get to know various possibilities it provides.

Drawing a Line

Example
<!DOCTYPE html>
<html>
<body>
  <canvas id="ThisIsCanvas" width="150" height="150" style="border:2px solid #000000;">
    HTML5 canvas tag is unsupported in your browser.
  </canvas>
<script>
  var c = document.getElementById("ThisIsCanvas");
  var ctx = c.getContext("2d");
  ctx.moveTo(0, 0);
  ctx.lineTo(150, 150);
  ctx.stroke();
</script>
</body>
</html>

Drawing a Circle

Example
<!DOCTYPE html>
<html>
<body>
  <canvas id="ThisIsCanvas" width="150" height="150" style="border: 2px solid #000000;">
    HTML5 canvas tag is unsupported in your browser.
  </canvas>
<script>
  var b = document.getElementById("ThisIsCanvas");
  var ctxx = b.getContext("2d");
  ctxx.beginPath();
  ctxx.arc(80, 70, 50, 0, 2*Math.PI);
  ctxx.stroke();
</script> 
</body>
</html>

Drawing a Text

Example
<!DOCTYPE html>
<html>
<body>
  <canvas id="ThisIsCanvas" width="150" height="150" style="border: 2px solid #000000;">
    HTML5 canvas tag is unsupported in your browser.
  </canvas>
<script>
  var b = document.getElementById("ThisIsCanvas");
  var ctx = b.getContext("2d");
  ctx.font = "20px Arial";
  ctx.fillText("I am the Cube", 10, 75);
</script>
</body>
</html>

Stroking a Text

Example
<!DOCTYPE html>
<html>
<body>
  <canvas id="ThisIsCanvas" width="150" height="150" style="border: 2px solid #000000;">
    HTML5 canvas tag is unsupported in your browser.
  </canvas>
<script>
  var b = document.getElementById("ThisIsCanvas");
  var ctxx = b.getContext("2d");
  ctxx.font = "20px Arial";
  ctxx.strokeText("I am the Cube", 10, 75);
</script>
</body>
</html>

Creating a Linear Gradient

Example
<!DOCTYPE html>
<html>
<body>
  <canvas id="ThisIsCanvas" width="150" height="150" style="border: 2px solid #000000;">
    HTML5 canvas tag is unsupported in your browser.
  </canvas>
<script>
  var b = document.getElementById("ThisIsCanvas");
  var ctx = b.getContext("2d");
  // Creating gradient
  var grad = ctx.createLinearGradient(0, 0, 160, 0);
  grad.addColorStop(0, "yellow");
  grad.addColorStop(1, "blue");
  // Filling with gradient
  ctx.fillStyle = grad;
  ctx.fillRect(10, 10, 130, 130);
</script>
</body>
</html>

Creating a Circular Gradient

Example
<!DOCTYPE html>
<html>
<body>
  <canvas id="ThisIsCanvas" width="150" height="150" style="border: 2px solid #000000;">
    HTML5 canvas tag is unsupported in your browser.
  </canvas>
<script>
  var b = document.getElementById("ThisIsCanvas");
  var ctx = b.getContext("2d");
  // Create gradient
  var grad = ctx.createRadialGradient(80, 45, 5,  80,50, 90);
  grad.addColorStop(0, "yellow");
  grad.addColorStop(1, "blue");
  // Fill with gradient
  ctx.fillStyle = grad;
  ctx.fillRect(10, 10, 130, 130);
</script>
</body>
</html>

Including an Image

Example
<!DOCTYPE html>
<html>
<body>
  <p>Use this image:</p>
  <img id="dragon" src="image.png" alt="The Dragon">
  <p>To fill this canvas:</p>
  <canvas id="ThisIsCanvas" width="215" height="215" style="border: 2px solid #d3d3d3;">
    HTML5 canvas tag is unsupported in your browser.
  </canvas>
  <p><button onclick="ThisIsCanvas()">Press it</button></p>
<script>
function ThisIsCanvas() {
  var b = document.getElementById("ThisIsCanvas");
  var ctx = b.getContext("2d");
  var img = document.getElementById("dragon");
  ctx.drawImage(img, 0, 0);
}
</script>
</body>
</html>

Get Your Own Canvas Drawing!

It's time to have some fun! This code example is a bit more complex than the others you saw in this simple HTML5 canvas tutorial. However, it is a perfect demonstration of what you can achieve using this element.

In it, you can draw a picture on the canvas using the cursor of your mouse and download it to your computer:

Example
var link = document.createElement('a');
link.innerHTML = 'Get this masterpiece!';
link.addEventListener('click', function (ev) {
  link.href = canvas.toDataURL();
  link.download = "masterpiece.png";
}, false);
document.body.appendChild(link);

HTML5 Canvas Tutorial: Useful Tips

  • Note that every HTML5 canvas element is blank by default and won't show until it's styled or has a drawing on it.
  • The default color of the drawing is black. To specify a different color, you can use either RGBA or HEX values.
  • Changing the height or width of the HTML5 canvas erases the drawing.