HTML5 Canvas Reference - beginPath()








The beginPath() method starts a path, or resets the current path.

After calling beginPath(), we can then use moveTo(), lineTo(), quadricCurveTo(), bezierCurveTo(), arcTo(), and arc(), to create sub-paths.

We have to use the stroke() method to actually draw the path on the canvas.

Browser compatibility

beginPath() Yes Yes Yes Yes Yes

JavaScript syntax

context.beginPath();




Example

The following code shows how to use beginPath from canvas context.


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!--from w  ww.j a  v  a 2  s .c  o m-->
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
    context.beginPath();
    context.moveTo(10, 10);
    context.lineTo(150, 50);
    context.stroke();
}
</script>
</head>
<body>
  <canvas id="myCanvas" width="578" height="200"></canvas>
</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to draw two paths on the canvas.


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    <!--from  w w w  .j  a va  2 s  .c o m-->
    ctx.beginPath();              
    ctx.lineWidth = "5";
    ctx.strokeStyle = "red";  // red path
    ctx.moveTo(0, 75);
    ctx.lineTo(350, 75);
    ctx.stroke();  // Draw it
    
    ctx.beginPath();
    ctx.strokeStyle = "purple";  // Purple path
    ctx.moveTo(50, 0);
    ctx.lineTo(250, 130);            
    ctx.stroke();  // Draw it
</script>
</body>
</html>

The code above is rendered as follows: