The first thing our run()
function really needs to do is to get hold of the canvas element to be able to do things with it, such as to draw shapes on it. This is where the id
attribute in the HTML becomes necessary. Our function will now start like this:
function run()
{
let cnv = document.getElementById("cnv");
// ...
}
When the browser opens an HTML file one of the first things it does is to build, in memory, a model of the page. This is called the DOM (Document Object Model). It contains data describing all of the elements in the page. The information is all linked to a document
object and that has some predefined functions available such as getElementById(id)
. So the example above is invoking that function (the dot shows it is part of the document
). And this function returns something that we need to keep hold of and use: a reference to the object in the DOM that describes the canvas element. So we define, using keyword let
and a made-up name cnv
, a place for keeping hold of that reference. The reference is placed there by the equals sign (it doesn't mean equality in the mathematical sense, instead it is the assignment operator, taking the result returned by the function on the right hand side and assigning it to the variable we have declared on the left).
Several new things have been introduced here, so take a while for it to sink in.
let
is a keyword for defining a "variable" named by us, that we can use again and again later within this function. The name we gave it, cnv
, only has to be unique within this function.
The id passed into getElementById()
is in quotes and that indicates that it is a string of characters, the same as was used for the id attribute in the HTML.
There is a line beginning //
. This means that the rest of that line is just a comment. It's for us to read but it means nothing to the browser. It is sometimes useful to add some comments but only if there is something unusual; do not repeat what the Javascript is saying. Clarity of naming and layout is important to enable programs to be maintained and perhaps enhanced in future and sometimes comments can help with that.