Home  >  Article  >  Web Front-end  >  Tutorial on using Canvas in HTML5 to draw a smiling face_html5 tutorial tips

Tutorial on using Canvas in HTML5 to draw a smiling face_html5 tutorial tips

WBOY
WBOYOriginal
2016-05-16 15:46:442398browse

201557180008373.jpg (600×436)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.

201557180130749.jpg (600×415)
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:

XML/HTML CodeCopy content to clipboard
  1. ><body>
  2.  <canvas id='canvas' width='640' height='480'>canvas>
  3.  <script type='text/ javascript' src='script.js'>script>
  4. body>html>

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