HTML5 Game - Canvas Shape Smiley

Drawing a Smiley using Paths

You can combine lines and curves to draw a path or a shape.

A path is a sequence of drawing operations that result in a shape.

A path can be open or closed.

A closed path can be filled with some color or pattern.

To draw a path, call the beginPath() method and then draw lines or curves.

To end the path, call stroke() to draw the outline of a shape or fill() to draw a filled shape.

The following code draws a smiley using the moveTo() and arc() methods.

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html lang="en">
 <head> 
  <meta charset="UTF-8"> 
  <title>HTML5 Canvas</title> 
  <script type="text/javascript">
    window.onload = function(){//from  ww w  .  j av  a 2  s . c  o  m
        let canvas = document.getElementById("myCanvas");
        let context = canvas.getContext("2d");
        // draw stuff here
         context.beginPath(); 
         //face 
         context.arc(100, 100, 80, 0, Math.PI * 2, false);  
         //smile 
         context.moveTo(160, 100); 
         context.arc(100, 100, 60, 0, Math.PI, false);  
         //left eye 
         context.moveTo(75, 70); 
         context.arc(65, 70, 10, 0, Math.PI * 2, true);  
         //right eye 
         context.moveTo(135, 70); 
         context.arc(125, 70, 10, 0, Math.PI * 2, true); 
         context.stroke(); 
    
         context.lineWidth = 5; 
         context.stroke(); 



        
    };
</script> 
 </head> 
 <body> 
  <canvas id="myCanvas" width="300" height="200"></canvas>   
 </body>
</html>

Note

There are four calls to the arc() method.

They draw the outline of the face, the smile, the left eye, and the right eye, respectively.

To draw the path, the code calls the stroke() method.

stroke() method draws the outline of the path.