Today, you will learn about a web technology called Canvas and its association with the Document Object Model (commonly known as DOM). This technology is very powerful as it enables web developers to access and modify HTML elements by using JavaScript.
Now you may be wondering why we need to go big with JavaScript. In short, HTML and JavaScript are interdependent, and some HTML components, such as the canvas element, cannot be used independently of JavaScript. After all, what good is a canvas if we can't draw on it?
To better understand this concept, let’s try drawing a simple smiley face through a sample project. Let's get started.
Start
Start by creating a new directory to save your project files, then open your favorite text editor or web development tool. Once you do this, you should create an empty index.html and an empty script.js, which we will continue editing later.
Next, let’s modify the index.html file, which won’t involve much since most of the code for our project will be written in JavaScript. What we need to do in HTML is create a canvas element and reference script.js, which is pretty straightforward:
To explain, I use a set of tags < html > and < body >, so that we can add more elements to the document through the body. Seizing this opportunity, I completed a 640*480 canvas element with the id attribute canvas.
This attribute simply adds a string to the element for unique identification. We will use this attribute later to locate our canvas element in the JavaScript file. Next, we reference the JavaScript file using the