Path

In this chapter you will learn:

  1. What are the methods we can use the draw path
  2. How to draw a path with lines

Drawing Using Paths

NameDescriptionReturns
beginPath()Begins a new pathvoid
closePath()Close a path by drawing a line from the end of the last line to the initial coordinatesvoid
fill()Fills the shapevoid
isPointInPath(x, y)Returns true if a point is contained by the current pathboolean
lineTo(x, y)Draws a sub-path to the specified coordinatesvoid
moveTo(x, y)Moves to the specified coordinates without drawingvoid
rect(x, y, w, h)Draws a rectangle whose top-left corners is at (x, y) with width w and height h.void
stroke()Draws the outline of the shapevoid

Drawing Paths with Lines

<!DOCTYPE HTML><!-- ja  v a  2 s  . c  o m-->
<html>
<head>
<style>
canvas {
      border: thin solid black
}

body>* {
      float: left;
}
</style>
</head>
<body>
      <canvas id="canvas" width="500" height="140"> 
      Your browser doesn't support the <code>canvas</code> element 
      </canvas>
      <script>
            var ctx = document.getElementById("canvas").getContext("2d");
            ctx.fillStyle = "yellow";
            ctx.strokeStyle = "black";
            ctx.lineWidth = 4;
            ctx.beginPath();
            ctx.moveTo(10, 10);
            ctx.lineTo(100, 10);
            ctx.lineTo(100, 120);
            ctx.closePath();
            ctx.fill();
            ctx.beginPath();
            ctx.moveTo(150, 10);
            ctx.lineTo(320, 10);
            ctx.lineTo(20, 120);
            ctx.lineTo(120, 120);
            ctx.fill();
            ctx.stroke();
            ctx.beginPath();
            ctx.moveTo(20, 10);
            ctx.lineTo(220, 120);
            ctx.stroke();
      </script>
</body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. How to draw arcs
  2. Using the arc Method
Home » Javascript Tutorial » Canvas
Canvas tag
Canvas Context
Rectangle
Rectangle clear
Drawing State
Drawing state restore
Line width
Line Join Style
Line cap settings
Gradients
Linear Gradient
Radial Gradient
Path
Arcs
Two types of curve
Quadratic Bezier Curves
Cubic Bezier Curves
Clip
Text
Shadow
Transparency
Stoke style