How it Works: Painting the Canvas
In this lesson, we will discuss the workings of the exercise on the canvas tag from the previous exercise. Let's begin!
We'll cover the following...
How it works
In step four, you defined the <canvas>
tag and set it up with the “myCanvas”
identifier. The page loads the drawing.js file in its <head>
section, so the <script>
placed right after the canvas knows the initDraw()
function, and invokes it with the id of the canvas passed.
The initDraw()
function does all initialization, and it invokes the draw()
method to paint the scenery:
function initDraw(elemId) {ctx = document.getElementById(elemId).getContext('2d');ballX = BALL;ballY = HEIGHT - BALL - SOIL - GRASS;draw();}
Line two is the most important, as it sets up the context object (ctx
), which can be used to draw shapes on the canvas. First using document.getElementById()
, it retrieves the object representing the “myCanvas”
element on the page. By invoking getContext('2d')
, it obtains a context object that allows drawing to a two-dimensional surface and stores it in ctx
.
📜NOTE: You’re probably asking yourself whether there is a three-dimensional drawing context based on the fact that a two-dimensional drawing context is used (“2d” in the code). Not yet, but the creators of HTML5 have left space for one in the future. There are frameworks using canvas with three-dimensional rendering, such as Babylon.js.
The <canvas>
element uses a coordinate system that designates its top-left corner as the point (). The canvas used in index.html has a width of , and a height of ...