w3resource

JavaScript: Draw a diagram using moveto() function

JavaScript Drawing: Exercise-5 with Solution

MoveTo Diagram

Write a JavaScript program to draw the following diagram [use the moveto() function].

Sample output:

draw fun

Sample Solution:

HTML Code:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Draw diagram using moveto() function</title>
</head>
<body onload="draw();">
<canvas id="canvas" width="250" height="250"></canvas>
</body>
</html>

JavaScript Code:

function draw() 
{
  var canvas = document.getElementById('canvas');
  if (canvas.getContext)
  {
    var context = canvas.getContext('2d');
    context.beginPath();
   // Outer circle
    context.arc(75,75,50,0,Math.PI*2,true);
    context.moveTo(110,75);
    // Mouth 
    context.arc(75,75,35,0,Math.PI,false); 
    // Lefy and Right eye
    context.moveTo(55,65);
    context.arc(60,65,5,0,Math.PI*2,true); 
    context.arc(90,65,5,0,Math.PI*2,true);
    context.stroke();
  }
}

Live Demo:

See the Pen javascript-drawing-exercise-5 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that uses moveTo() and lineTo() to draw a star shape with multiple points.
  • Write a JavaScript program that draws a simple house diagram (with a roof, door, and windows) using moveTo() and lineTo().
  • Write a JavaScript program that creates a zigzag pattern across the canvas using moveTo() for starting each line segment.
  • Write a JavaScript program that draws a regular polygon (e.g., hexagon) by calculating vertices and connecting them with moveTo() and lineTo().

Go to:


PREV : Right-Angled Triangle.
NEXT : Diagonal Gradient Circles.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.