Category Archives: HTML5 Canvas

Drawing quadratic curves

This tutorial explains how to draw quadratic curves on the HTML canvas. We can use the quadraticCurveTo() method to draw a quadratic curve on the canvas.

The quadratic curve is defined by three things: the context point, the control point, and the ending point. These curves can also be styled using the lineWidth, stroke style and lineCap properties just like regular lines.

Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>Quadratic curves</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
</head>
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.moveTo(50,50);
 ctx.lineTo(300,50);
 ctx.quadraticCurveTo(300,100,350,100); // (control point x, control point y, x, y)
 ctx.lineTo(350,200);
 ctx.stroke();
 }
 window.onload = draw;
 </script>
 
 <canvas id="myCanvas" width="500" height="350">
</body>
</html>

Drawing arcs using the arcTo method

This tutorial explains how to draw arcs using the arcTo method. You will learn how to draw arcs and join arcs to other lines on the canvas.

This is what the arc attached to lines will look like:

Screen Shot 2015-05-08 at 6.56.39 pm

Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>The arcTo method</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
</head>
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.moveTo(50,50);
 ctx.lineTo(200,50);
 ctx.arcTo(250,50,250,100,50); // x1, y1, x2, y2, radius
 ctx.lineTo(250,200);
 ctx.stroke();
 }
 window.onload = draw;
 </script>
 
 <canvas id="myCanvas" width="500" height="350">
</body>
</html>

Next tutorial: Drawing quadratic curves

Clipping shapes on the canvas

This tutorial will explain how to clip shapes on the canvas. The clipped shape example in the video will look like this:

Screen Shot 2015-05-08 at 7.01.35 pm

Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>Clipping shapes</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
</head>
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.rect(50, 50, 100, 100) // x, y, width, height
 // we will clip one rectangle with the other 
 ctx.clip();
 ctx.rect(0, 0, 100, 100)
 ctx.stroke();
 }
 window.onload = draw;
 </script>
 
 <canvas id="myCanvas" width="200" height="200">
</body>
</html>

Next tutorial: Drawing arcs and circles on the canvas

Drawing paths on the canvas

This tutorial explains how to draw paths on the canvas. Paths can be used to build shapes by creating lines, filling the path, and filling the background with a colour, as seen in the example below.

Screen Shot 2017-04-14 at 5.06.13 pm

Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>Drawing paths</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
</head>
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.beginPath(); // this will reset the current default path
 ctx.moveTo(50,50); // x, y coordinates of start of line
 ctx.lineTo(250,50); // creates new line to these x, y coordinates
 ctx.lineTo(250,150); // creates another line to these x, y coordinates
 ctx.lineTo(50,150);
 ctx.fill();
 ctx.closePath(); // this will close the path to complete the rectangle (adds the last line on the left side of rectangle)
 ctx.stroke(); // strokes the current path
 alert(ctx.isPointInPath(75,75)); // returns a true/false value indicating whether the specified point is within a path
 }
 window.onload = draw;
 </script>
 
 <canvas id="myCanvas" width="500" height="350">
</body>
</html>

Next tutorial: Clipping shapes on the canvas

Joining lines on the canvas

This tutorial explains how to join lines on the canvas. The lines that we will join in this tutorial will end up looking like this:

Screen Shot 2015-05-08 at 6.59.43 pm

Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>Joining lines</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
</head>
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.lineWidth = 20;
 ctx.lineCap = "butt"; // options are: square, round, butt
 ctx.lineJoin = "round"; // options are: round, bevel, miter
 //ctx.miterLimit = 3;
 //ctx.setLineDash([20,10]); //adds dashes -length of dash,length of gap between dash
 //ctx.lineDashOffset = 20;
 
 ctx.beginPath();
 ctx.moveTo(50,50);
 ctx.lineTo(150,250);
 ctx.lineTo(250,50);
 ctx.lineTo(150,50);
 ctx.strokeStyle="#FF0000";
 ctx.stroke();
 //ctx.fill(); will add a fill
 }
 window.onload = draw;
 </script>
 
 <canvas id="myCanvas" width="300" height="300">
</body>
</html>

Next tutorial: Drawing paths on the canvas

Styling lines on the canvas

In the previous tutorial we looked at how to draw lines on the canvas. In this tutorial we will style lines on the canvas by changing the following properties:

  • colour
  • width
  • line cap (shape on the ends of a line) for a line on the canvas

The line that we will create will look like this:

Screen Shot 2015-05-08 at 6.58.05 pm

Watch the video below and then scroll down the page to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
 <title>Styling lines on the canvas</title>
 <style>
 #myCanvas{
 background-color:#FFFFFF;
 border: 1px solid #000000;
 }
 </style>
</head>
 
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.lineWidth=20; // specify the width of the line
 ctx.lineCap="round"; // lineCap options are square, round, butt
 ctx.moveTo(50,50); // x,y positions - where the line begins
 ctx.lineTo(250,250); // x,y positions - where the line ends
 ctx.strokeStyle="#0000FF"; // specify the colour of the line
 ctx.stroke(); // draw the line
 }
 window.onload=draw; // run the draw function when the page loads
 </script>
 <canvas id="myCanvas" width="300" height="300">
</body>
</html>

Next tutorial: Joining lines on the canvas

Using colour gradients and patterns

The code below shows how to use linear and radial gradients to fill rectangle shapes.

The three shapes will look like this (linear gradient on top left, radial gradient on top right, image pattern on bottom left side):

Screen Shot 2015-05-08 at 6.53.39 pm

Watch the video below and then scroll down to see the sample code.

Here is the code:

<!DOCTYPE html>
<html>
<head>
 <title>Gradients and patterns</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
 <script>
 var patternImage = new Image();
 patternImage.src = "pattern.png";
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 var gradient = ctx.createLinearGradient(0,0,150,0); // x1, y1, x2, y2 
 gradient.addColorStop(0, "red");
 gradient.addColorStop(0.5, "yellow");
 gradient.addColorStop(1, "green");
 ctx.fillStyle = gradient;
 ctx.strokeStyle = "blue";
 ctx.fillRect(0,0,150,75);
 ctx.strokeRect(0,0,150,75);
 
 var gradient2 = ctx.createRadialGradient(350,100,0,350,100,200);
 // ctx.createRadialGradient parameters are x1, y1, r1, x2, y2, r2
 gradient2.addColorStop(0, "yellow");
 gradient2.addColorStop(1, "blue");
 ctx.fillStyle = gradient2;
 ctx.strokeStyle = "blue";
 ctx.fillRect(250,0,200,200);
 ctx.strokeRect(250,0,200,200);
 
 var pattern = ctx.createPattern(patternImage, "repeat");
 ctx.fillStyle = pattern;
 ctx.strokeStyle = gradient;
 ctx.lineWidth = 20;
 ctx.fillRect(20,150,200,200);
 ctx.strokeRect(20,150,200,200);
 }
 window.onload=draw;
 </script>
</head>
<body>
 <canvas id="myCanvas" width="500" height="400">
</body>
</html>

Next tutorial: Simple animations using JavaScript

Animating an image using JavaScript

This tutorial shows how to animate (move) an image across the screen. You can combine the code with other code from previous tutorials such as the one on timed image swapping to also get images to swap while they are moving (eg. you could use two images for a character with legs in different positions, so as the images swap it looks like the character is running).

You will need an image to use in your animation. Keep the image file in the same folder as your HTML file. In the sample code below, the image’s file name is image.png (a PNG image file). Start and stop buttons have also been added to start/stop the animation. This is what the animation will look like:

imageanimated

Refer to the comments in the code below to find out what is happening on each line.

<html>
<head>
<title>JavaScript Image Animation</title>
<script type="text/javascript">
<!--
var imgObj ;
var animate ;
function init(){
 imgObj = document.getElementById('myImage');
 imgObj.style.position= 'relative'; 
 imgObj.style.left = '0px'; 
}
function moveRight(){
 imgObj.style.left = parseInt(imgObj.style.left) + 5 + 'px'; // move from the left 5 pixels
 animate = setTimeout(moveRight,20); // call moveRight in 20 milliseconds
}
function stop(){
 clearTimeout(animate); // stops the animation
 // add imgObj.style.left = '0px'; if you want to reset the image back to the left side of screen
}
window.onload =init; // starts animation when page loads
//-->
</script>
</head>
<body>
<form>
<img id="myImage" src="image.png" width="100" height="100"/>
<p>Click the buttons below to start and stop the animation.</p>
<input type="button" value="Play" onclick="moveRight();" />
<input type="button" value="Stop" onclick="stop();" />
</form>
</body>
</html>

Next tutorial: Keyboard events in JavaScript

Simple animations using JavaScript

This tutorial explains how to use the HTML5 canvas element and JavaScript to animate a div in a webpage. Below is a preview of what the animation will look like. Scroll down to see the code.

animdiv

Refer to the comments in the code below to find out what is happening on each line.

<html>
<head>
<title>My animation</title>
<style type="text/css">
 
#animatedBox{
 /* simple box */
 position:absolute; /* The element is positioned relative to its first positioned (not static) ancestor element */
 top:30px; /* This is the position of the box from the top */
 width:200px; /* This is the width of the box */
 line-height:20px; /* This is the height of the box */
 background:#58FA82; /* This is the background colour of the box */
 border:1px solid #0B610B; /* This is the border thickness and border colour of the box */
 padding:10px; /* This is the padding amount around the text in the box */
 
 /* Hint: Get colour codes from http://html-color-codes.info/ */
}
 
</style>
<script type="text/javascript">
 
var box ; // create the variable we will use as the object to animate
 
function doMove() {
 box.style.left = parseInt(box.style.left)+1+'px'; // parseInt parses a string and returns an integer, moves 1 pixel from left
 setTimeout(doMove,20); // call doMove in 20 milliseconds
}
 
function init() {
 box = document.getElementById('animatedBox'); // get the "box" object
 box.style.left = '0px'; // set its initial position to 0px
 doMove(); // call the doMove function to start animating!
}
 
 
window.onload = init; // load the init function when the page loads
 
</script>
</head>
 
<body>
 
<div id="animatedBox">
 <b>My animation</b>
</div>
 
</body>
</html>

Next tutorial: Animating (moving) an image using JavaScript

Drawing arcs and circles with the HTML5 canvas

This tutorial explains how to use the HTML5 canvas and JavaScript to draw circles and arcs on the canvas. The code below shows how to draw a full circle, but you can easily modify it to draw arcs (the circle is made up of arcs).

In this example, the circle will be inside a canvas with a black border and will look like this:

Screen Shot 2015-03-12 at 10.47.58 am

Watch the video below and then scroll down to see the sample code.

Refer to the comments in the code to find out what is happening on each line of the code.

<!DOCTYPE html>
<html>
<head>
 <title>Arcs and circles</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
</head>
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.arc(150,150,100,0,Math.PI*2,false); // x, y, radius, startAngle, endAngle, true/false (for clockwise and anticlockwise)
 // Math.PI gives semi-circle
 // Math.PI*2 gives full circle
 // Numbers can also be used instead of Math.P eg. 6.28
 // try using numbers less than 6.28 to see how you get less of a circle
 ctx.stroke();
 //try doing semi-circle that is (flipped over) by chaning false to true
 
 }
 window.onload = draw;
 </script>
 
 <canvas id="myCanvas" width="500" height="350">
</body>
</html>

Next tutorial: Drawing arcs using the arcTo method

Drawing lines using the HTML5 canvas

This tutorial explains how to use the HTML5 canvas element to draw lines. The line that will be drawn will be inside a canvas with a  grey border. It will look like this:

Screen Shot 2015-05-04 at 8.51.12 pm

Watch the video below to see how to draw lines and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>Drawing lines on canvas</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
</head>
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.moveTo(0,0);
 ctx.lineTo(200,100);
 ctx.strokeStyle="#FF0000";
 ctx.stroke();
 }
 window.onload = draw;
 </script>
 
 <canvas id="myCanvas" width="200" height="100">
</body>
</html>

Next tutorial: Styling lines on the canvas

Using the HTML5 canvas to draw shapes

The code below shows how to use the HTML5 canvas and JavaScript in a webpage to draw objects. In this example, the object will be a simple rectangle shape inside a canvas with a grey border. The rectangle will be filled with red and have a blue border. It will look like this:

Screen Shot 2015-05-04 at 7.53.26 pm

You can use the canvas for drawings, animations, and even games. Watch the video below to see how to create a canvas and draw a rectangle shape, then scroll down to see the code.

Check out the sample code below. You can view all the different HTML colour codes that you can use here.

<!DOCTYPE html>
<html>
<head>
 <title>Simple canvas with rectangle drawing</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.fillStyle = "red";
 ctx.strokeStyle = "blue";
 ctx.fillRect(0,0,150,75);
 ctx.strokeRect(0,0,150,75);
 }
 window.onload=draw;
 </script>
</head>
<body>
 <canvas id="myCanvas" width="200" height="100">
</body>
</html>

Next tutorial: Drawing lines using the HTML5 canvas element