Copyright

Advanced Canvas Features in HTML: Use & Examples

Instructor: Alexis Kypridemos

Alexis is a technical writer for an IT company and has worked in publishing as a writer, editor and web designer. He has a BA in Communication.

In this lesson, we'll demonstrate through code examples how to use some advanced features of the HTML 5 canvas, such as gradients, shape filling, drop shadow and rotation.

HTML 5 Canvas Advanced Features

Lesson Overview

You learned about the HTML 5 canvas element in a previous lesson: https://study.com/academy/lesson/the-html-5-canvas-definition-purpose-examples.html. In this lesson, we'll demonstrate how to use some of the more advanced features of the canvas, such as:

  • Applying gradients
  • Filling shapes
  • Drop shadows
  • Rotating the canvas

It is not required, but we advise copying and pasting the code example below into an online HTML or JavaScript editor, or saving it as an .html file on your computer and opening it in a web browser. This way, you get to see the code in action.

Let's first have a look at some HTML and JavaScript code that includes all the features we mentioned above, and then we'll break it down one line at a time to see how it works:

<!DOCTYPE html>
<html>
<body>
<canvas style="width: 600px; height: 600px;">
</canvas>
<script>
var canvas = document.getElementsByTagName("canvas")[0];
var context = canvas.getContext("2d");
var gradient = context.createLinearGradient(60, -60, 300, 0);
gradient.addColorStop(0, "black");
gradient.addColorStop(1, "white");
context.rotate(50 * Math.PI / 180);
context.shadowOffsetX = 10;
context.shadowOffsetY = 10;
context.shadowColor = "red";
context.shadowBlur = 10;
context.fillStyle = gradient;
context.fillRect(60, -60, 100, 80);
</script>
</body>
</html>


Creating the Canvas

In the code above, the HTML portion only contains the <canvas> element, and uses inline CSS style rules to give it width and height of 600 pixels on each side:

<canvas style=''width: 600px; height: 600px''>
</canvas>


Drawing with JavaScript

The bulk of the code is contained in the <script> element, and is, of course, JavaScript. The JavaScript commands do the actual 'drawing' inside the HTML canvas.

The first two lines of the JavaScript code identify the HTML canvas element, and create the two-dimensional context object, which we need to set up before we can perform further operations on the canvas, including basic operations like drawing shapes. You saw how to do this in the previous lesson.

var canvas = document.getElementsByTagName("canvas")[0];
var context = canvas.getContext("2d");


Although not the focus of this lesson, let's briefly explain the second line used here. The variable context is created. In it, we store the result of using the getContext() method. This method takes the context type as its parameter from a list of possible values. In this case, we use the value 2d to create a two-dimensional rendering context, or, put simply, a 'flat', rectangular 'surface' to draw on. You can read more about the values that can be entered as this method's parameter here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext.

Code Sequence

Before we dive into the nuts and bolts of how to use these advanced canvas features, let's point out that the commands for adding gradients, rotating the canvas, and so on must be included in the JavaScript code before the commands that draw the shape, otherwise we won't get the expected results.


Creating Gradients

A gradient allows us to give our shape the appearance of having one color which gradually fades into another. The HTML 5 canvas supports two types of gradients:

  • linear, which fades the color from left to right or vice versa;
  • radial, which fades the color from all edges of the canvas to its center.

It's important to remember that the gradient is applied to the entire context object, and not just the shape drawn inside the canvas.

In our example, we use a linear gradient, to give the context a gradual fade from black on the left to white on the right. To do this, we use these three lines of code:

var gradient = context.createLinearGradient(60, -60, 300, 0);
gradient.addColorStop(0, "black");
gradient.addColorStop(1, "white");

With the first line, we create the variable gradient. In it, we store the result of applying the createLinearGradient() method on the context object. The createLinearGradient() method takes four parameters: the x and y coordinates of where the gradient begins, followed by the coordinates of where the gradient stops. In this case, the gradient begins at 60, -60 (60 pixels to the right of canvas' left edge, and 60 pixels above the top edge) and ends at 300, 0 (300 pixels to the right of the canvas' left edge and level with the top edge).

With the next two lines, we use the addColorStop() method twice on the gradient variable, to specify the gradient's colors. We use two colors in this example, but we could use more if wanted to. The addColorStop() method takes two parameters: a position, from 0 to 1, and a color. In this case, we use the colors black and white, and the positions 0 and 1 respectively.


Rotating the Canvas

As with gradients, rotation applies to the entire context object, and not only to a specific shape. The degree of rotation is provided in radians, and its direction is clockwise. We achieve rotation using the rotate() method. In our example, we rotate the context object 50 degrees clockwise with this line:

context.rotate(50 * Math.PI / 180);

* Math.PI / 180 represents radians, or degrees of rotation.


To unlock this lesson you must be a Study.com Member.
Create your account

Register to view this lesson

Are you a student or a teacher?

Unlock Your Education

See for yourself why 30 million people use Study.com

Become a Study.com member and start learning now.
Become a Member  Back
What teachers are saying about Study.com
Try it risk-free for 30 days

Earning College Credit

Did you know… We have over 160 college courses that prepare you to earn credit by exam that is accepted by over 1,500 colleges and universities. You can test out of the first two years of college and save thousands off your degree. Anyone can earn credit-by-exam regardless of age or education level.

To learn more, visit our Earning Credit Page

Transferring credit to the school of your choice

Not sure what college you want to attend yet? Study.com has thousands of articles about every imaginable degree, area of study and career path that can help you find the school that's right for you.

Create an account to start this course today
Try it risk-free for 30 days!
Create An Account
Support