Step 1
Create an HTML file Index.html and inside that add a canvas, give it a width of 400 and height of 200.
- <!DOCTYPE html>
- <html>
- <head>
- <title>
- HTML CANVAS
- </title> <!—a reference to the an external js file-->
- <script src="script.js"></script>
- </head>
- <body onload="bodyLoad()">
- <canvas id="mycanvas" width="400" height="200" onmousewheel="myfunction2();"></canvas>
- </body>
- </html>
Step 2
The next step is to create a JavaScript file “script.js”. In that JavaScript file create a function myFace.
To get the element reference of Canvas we can use its Id “myCanvas”. Pass it in the GetElementById function as a parameter which is present in the global variable document.
- function myFace() {
- var c = document.getElementById("mycanvas");
-
-
- var draw = c.getContext("2d");
-
-
-
- draw.beginPath();
-
-
- draw.fillStyle = "yellow";
-
-
-
- draw.arc(75, 75, 50, 0, Math.PI * 2, true);
-
-
- draw.closePath();
-
-
- draw.fill();
- }
Call this function when the body content loads, in other words on:
- <body onload="myfunction()">
- <body onload="myFace()">
- <p>Scroll your mouse over my face</p>
- <canvas id="mycanvas" width="400" height="200"></canvas>
- </body>
Save and open the HTML file using a web browser and the output will look like the following:
So, we have created a smiley face.
Step 3
The next thing we need to do is to add eyes to this face.
- function myEye() {
- var c = document.getElementById("mycanvas");
- var eye = c.getContext("2d");
-
-
- eye.moveTo(55, 50);
-
-
- eye.beginPath();
-
-
- eye.fillStyle = "black";
-
-
- eye.arc(50, 50, 4, 0, Math.PI * 2, true);
- eye.closePath();
- eye.fill();
-
-
- eye.moveTo(103, 49);
-
- eye.beginPath();
- eye.fillStyle = "black";
-
- eye.arc(100, 50, 4, 0, Math.PI * 2, true);
- eye.closePath();
- eye.fill();
- }
Create a new function and add myFace and myEye functions to it.
- function bodyLoad() {
- myFace();
- myEye();
- }
Pass this bodyLoad function in the onload event of the body element.
- <body onload="bodyLoad()">
Refresh the page.
Step 4
The final step is to add a smile.
Create a new function, mySmile and add the following:
- function mySmile() {
- var c = document.getElementById("mycanvas");
- var smile = c.getContext("2d");
-
- smile.moveTo(105, 75);
- smile.beginPath();
- smile.strokeStyle = "red";
- smile.arc(75, 75, 30, 0, Math.PI, false);
-
- smile.stroke();
- }
- Add mySmile function in bodyLoad function.
-
- function bodyLoad() {
- myFace();
- myEye();
- mySmile();
- }
Save and run it.
To learn more about Canvas Rendering
click here.
I hope you like it. Thank you.