In this article, we are going to show you how to use the <canvas> element as outlined in Skilled.co's Canvas cheat sheet. You will have a basic understanding of how to write script using this element by the end of this article.
Keep in mind that the skills outlined in this brief tutorial are only the barest skills needed to use the <canvas> element. Even so, they are among the most critical skills and commands that you will need throughout your entire experience with Canvas. Learning the basics will provide the designer with a solid foundation from which to build more extensive skills with Canvas as time goes on. So, we will now begin with our example <canvas> element and start down the rabbit hole.
The Canvas element part is structured:
<canvas> … </canvas>
Inside this command, you will include identification:
<canvas> canvas id="Example" … </canvas>
Be sure to surround the element identification with quotes. Then, you will need to include height and width parameters after the identification. The final product should look like this:
<canvas> canvas id="Example" width=150 height=60> </canvas>
If your browser is out of date, you will be prompted with a "fallback" message that tells you to update your browser first.
This part of the script is broken up into three steps for three separate commands:
First, we need to load the HTML <canvas> tag. We called it "Canvas" and accomplished the loading process in our example by saving it within a variable:
[var canvas = document.getElementById('ExampleCanvas')]
The image does not directly generate in the HTMLCanvasElement. It generates in its context, which is an internal CanvasRenderingContext2D object. We saved the object in another variable and named it:
[var context = canvas.getContext('2d').]
We are ready to draw and create! This is easily accomplished by modifying properties like color by calling methods:
context.fillStyle = 'red';
The above method will make the object red.
The above method will generate [.fillRect (0,0,150,60);]
context.fillStyle = 'yellow';
The above method will make the object yellow.
The above method will create [context.fillRect (5,5,140,50)]
context.fillStyle = 'red';
The above method will return the object back to red.
context.font = '40pt Arial';
The above method will specify the font.
The above method will write the text, "Hello."
The picture is generated in the context and describes all of its needs for execution. This is the bulk of using the <canvas> element. These basic steps should give you a basic understanding and a solid foundation to work from while using Canvas to create interesting designs.
Editor’s note: There are several other commands that you can experiment with in the cheat sheet, which you can find here.
Rojenx is a leading concept artist who work appears in games and publications
Check out his personal gallery here