I'm going to show you a very basic example of canvas use.
So, we will first declare a canvas element.
Give it an ID, this is a good practice,
I call it "myCanvas", and may be give it a width and a height.
Here a width of 200 pixels and a height of 200 pixels.
And between the opening and closing elements, usually we write a small message saying that "Canvas is not supported by your browser… ».
This is just in case you run this example on a very old Internet Explorer.
Once we declared the canvas, usually, we go to the JavaScript part of the code.
So here, I'm using jsbin.com, a web-based IDE that has a nice separation of the different parts.
So I will write the JavaScript part here.
I write a function called "init", where we are going to initialize the interesting parts.
So, let's get the canvas using
the DOM API.
I’m going to use querySelector() that is a more recent method from the DOM API.
QuerySelector is interesting because you can use CSS selectors, here is a # sign for the ID... and now I'm getting the context from the canvas.
We specify '2d' because it's possible also to ask for a context for webGL, that is not covered in this course.
I'm declaring the different variables here.
And once I've got the context I can draw.
The first function we are going to look at is fillRect, that draws a filled rectangle, at a given position. Here x=10, y=10 with a given width and height of 100.
Nothing appears on the output tab because I need to indicate that this function is called when the page has been loaded.
window.onload = init; so, like that if I run the code I can see the result.
So when the document has been loaded the init function is called and inside this function I get the canvas, I get the context from the canvas that will be useful for drawing.
I can draw another rectangle here... at another position, with a different size like that... I can also specify the color.
It is the fillStyle property of the context that is used... it takes as a value a CSS color.
You can see that the first rectangle is black because this is the default color, and the second one is red, because I’ve just indicated that...
If I move this line before the two drawing orders, all the consecutive drawings will be red.
So, it's a kind of "global variable"
If I want a red rectangle and a blue one, I need to duplicate that...
So this is a very basic example, and when your drawings become complex, it's a good practice to cut your code in functions..., like that, then call it once...
Here we are...like that...
So you've got the html code here, the JavaScript code and the results. If you want to store this for... writing it onto your hard disk, you can use the file menu
I need to zoom out.... file/download.
And it will download an HTML page.
If you open the HTML page, you've got the code you wrote inside.
And if you look at the source code, you will find the JavaScript as a script element.
Small errata about what I said in the above video: "So let's get the canvas using the DOM API method document.getElementById() or better, use document.querySelector() that is a more recent method from the DOM API".
The part in bold is not correct: querySelector, technically, comes from Selectors API. Just in case some people would like to check the specification.
Here are the different steps, in a little more detail, of the example demonstrated in the above video:
<canvas id="myCanvas" width="300" height="225">
Fallback content that will be displayed in case the web browser does not
support the canvas element or in case scripting is disabled.
</canvas>
Place code similar to the above somewhere in an HTML page. This example defines an area of 300 by 225 pixels on which content can be rendered with JavaScript.
Normally you should see nothing as a result; by default canvases are "transparent". Make it visible using CSS!
For example, you can add a border to the canvas (or change the background color, or put an image in the background).
The three lines of CSS will create a border around the canvas with id="myCanvas", of 1 pixel width, in black:
style>
#myCanvas {
border:1px solid black;
}
</style>
We can have more than one <canvas> in a single page, and canvases will be manipulated with JavaScript like other elements in the DOM.
For example with:
var canvas = document.getElementById("myCanvas");
... or with the querySelector() method introduced by HTML5, that use the CSS selector syntax for selecting elements:
var canvas = document.querySelector("#myCanvas");
This step is useful for drawing and setting drawing properties (color, etc.)
Once we have a pointer to the <canvas>, we can get a "context". This particular object is the core of the canvas JavaScript API. It provides methods for drawing, like fillRect(x, y, width, height) for example, that draws a filled rectangle, and properties for setting the color, shadows, gradients, etc.
So, let's first get the context (do this only once):
var ctx=canvas.getContext('2d');
... then, set the color for drawing filled shapes:
ctx.fillStyle='red';
... and draw a filled rectangle:
ctx.fillRect(0,0,80,100);
Source code:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
#myCanvas {
border: 1px solid black;
}
</style>
<title>Canvas</title>
<meta charset="utf-8"/>
<script>
var canvas, ctx;
function init() {
// This function is called after the page is loaded
// 1 - Get the canvas
canvas = document.getElementById('myCanvas');
// 2 - Get the context
ctx=canvas.getContext('2d');
// 3 - we can draw
drawSomething();
}
function drawSomething() {
// draw a red rectangle
ctx.fillStyle='#FF0000';
ctx.fillRect(0,0,80,100);
}
</script>
</head>
<body onload="init();">
<canvas id="myCanvas" width="200" height="200">
Your browser does not support the canvas element.
</canvas>
</body>
</html>
Notice that we wrote an "init" function (line 13) that is called only when the page has been entirely loaded (we say "when the DOM is ready"). There are several ways to do this. In this example we used the <body onload="init();"> method, at line 29.
It's good practice to have such a function, as we cannot access the elements of the page before the page has been loaded entirely and before the DOM is ready.
Another way is to put the JavaScript code at the end of the document (between <script>...</script>), right before the </body>. In this case when the JavaScript code is executed, the DOM has already been constructed.
Before drawing or doing anything interesting with the canvas, we must first get its drawing "context". The drawing context defines the drawing methods and properties we can use.
Good practice is to get the canvas, the context, the width and height of the canvas and other global objects in this "init" function.
The example shows the use of the fillStyle property at line 24 - useful for specifying the way shapes will be filled. In our case this line indicates the color of all the filled shapes we are going to draw:
ctx.fillStyle='#FF0000';
The context property named fillStyle is used here. This property can be set with a color, a gradient, or a pattern. We will see examples of these later on in the course.
The example says that all filled shapes will use the color "#FF0000", which corresponds to a pure red color using the CSS RGB hexadecimal encoding (we could also have used ctx.fillStyle='red');
ctx.fillRect(0,0,80,100);
This line is a call to the method fillRect(top left X coordinate, top left Y coordinate, width, height), which draws a filled rectangle.
The way the rectangle will be filled depends on the current value of several properties of the context, in particular the value of the fillStyle property. So, in our case, the rectangle will be red.
Declare the canvas, remembering to add an id attribute, and fallback content: <canvas id="myCanvas" width="200" height="200"> ...fallback content... </canvas>
Get a reference to the canvas in a JavaScript variable using the DOM API (for example): var canvas=document.getElementById('myCanvas');
Get the context for drawing in that canvas: var ctx=canvas.getContext('2d');
Specify some drawing properties (optional): ctx.fillStyle='#FF0000';
Draw some shapes: ctx.fillRect(0,0,80,100)