Using canvas in HTML5 to draw a smiling face tutorial

Time:2022-1-3

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 because it enables web developers to access and modify HTML elements by using JavaScript.

Now you may wonder why we need to use JavaScript aggressively. In short, HTML and JavaScript are interdependent. Some HTML components, such as canvas elements, cannot be used separately from JavaScript. After all, if we can’t draw on it, what can canvas do?

To better understand this concept, let’s try to draw a simple smiling face through an example project. Let’s start.
start

First create a new directory to save your project files, and then open your favorite text editor or web development tool. Once you do, you should create an empty index HTML and an empty script JS, after which we will continue to edit.

201557180130749.jpg (600×415)
Next, let’s modify the index HTML file, which won’t involve much, because most of the code of our project will be written in JavaScript. What we need to do in html is to create a canvas element and reference script JS, which is quite straightforward:
 

XML/HTML CodeCopy contents to clipboard
  1. <!DOCTYPE html><body>  
  2.     
  3.    <canvas id=‘canvas’ width=‘640’ height=‘480’></canvas>  
  4.    <script type=‘text/javascript’ src=‘script.js’></script>  
  5.     
  6. </body></html>  
  7.   

To explain this, I use a set of tags < HTML > and < body >, so that we can add more elements to the document through body. Seizing this opportunity, I completed a canvas element with ID attribute of 640 * 480.

This attribute simply adds a string to the element for unique identification. Later, we will use this attribute to locate our canvas element in the JavaScript file. Next, we use the < script > tag to reference the JavaScript file, which specifies the language type of JavaScript and script JS file path.
Operation DOM

As its name is “document object model”, we need to use another language to call the interface to access HTML documents. Here, the language we use is JavaScript. To do this, we need to arrange a simple reference on the built-in document object. This object directly corresponds to our < HTML > tag. Similarly, it is the basis of the whole project, because we can get elements and perform changes through it.
 

XML/HTML CodeCopy contents to clipboard
  1. var canvas = document.getElementById(‘canvas’);   
  2.   

Remember how we used id = “canvas” to define a canvas element? Now let’s use document Getelementbyid method, get this element from the HTML document, and we simply pass a string matching the required element ID. Now that we have obtained this element, we can use it for painting.

In order to use canvas for painting, we must manipulate its context. Surprisingly, a canvas does not contain any drawing methods or properties, but its context object has all the methods we need. A context is defined as follows:

XML/HTML CodeCopy contents to clipboard
  1. var context = canvas.getContext(‘2d’);   
  2.   

Each canvas has several different contexts. According to the purpose of the program, only a two-dimensional context is enough. It will get all the drawing methods we need to create smiling faces.

Before we start, I must tell you that the context stores two color attributes, one for stroke and one for fill. For our smiling faces, we need to set the fill to yellow and the brush to black.
 

XML/HTML CodeCopy contents to clipboard
  1. context.fillStyle = ‘yellow’;   
  2. context.strokeStyle = ‘black’;   
  3.   

After setting the color required for the context, we must draw a circle for the face. Unfortunately, there is no predefined method for circles in the context, so we need to use the so-called path. The path is just a series of connected lines and curves. The path is closed after the drawing is completed.
 

XML/HTML CodeCopy contents to clipboard
  1. context.beginPath();   
  2. context.arc(320, 240, 200, 0, 2 * Math.PI);   
  3. context.fill();   
  4. context.stroke();   
  5. context.closePath();   
  6.   

In this way, we use context to start a new path. Next, we create an arc with a radius of 200 pixels on the points (320, 240). The last two parameters specify the initial and final angles of the construction arc, so we pass 0 and 2 * math Pi to create a complete circle. Finally, we use context to fill and draw the path based on the color we have set.

Although closing the path is not necessary for the function of the script, we still need to close the path so that we can start drawing new eyes and mouths in the smiling face. Eyes can be done in the same way, and each eye needs a smaller radius and different position. But first we must remember to set the fill color to white.
 

XML/HTML CodeCopy contents to clipboard
  1. context.fillStyle = ‘white’;   
  2.     
  3. context.beginPath();   
  4. context.arc(270, 175, 30, 0, 2 * Math.PI);   
  5. context.fill();   
  6. context.stroke();   
  7. context.closePath();   
  8.     
  9. context.beginPath();   
  10. context.arc(370, 175, 30, 0, 2 * Math.PI);   
  11. context.fill();   
  12. context.stroke();   
  13. context.closePath();   
  14.   

The above is all the code about the eyes. Now the mouth is very similar, but this time we won’t fill the arc, our angle will be configured as a semicircle. To do this, we need to set the start angle to zero and the end angle to – 1 * math PI。 Remember, don’t forget to set the color of the brush to red.
 

XML/HTML CodeCopy contents to clipboard
  1. context.fillStyle = ‘red’;   
  2.     
  3. context.beginPath();   
  4. context.arc(320, 240, 150, 0, -1 * Math.PI);   
  5. context.fill()   
  6. context.stroke();   
  7. context.closePath();   

congratulate

Well done. You have completed this tutorial, you have made a great smile, and learned more about canvas, HTML, JavaScript, and document object model. If you have any questions, please leave a message.

Recommended Today

Take you to “experience” redis master-slave replication

Redis series: 🐯Redis installation tutorial (nanny level detailed graphic) 🐯Installation steps of bron filter 🐯Remember the first-hand “redis persistence mechanism” 🐯Hands on RDB & AOF 🐯Take you to “experience” redis master-slave replication 🐯“Redis sentry” is a thief cool~ 🐯Tweetproxy of “redis proxy” Redis uses the default asynchronous replication, which is characterized by low latency and […]