HTML Canvas - getLineDash() Method



The HTML Canvas getLineDash() method of Canvas API is from the CanvasRenderingContext2D interface and is when called by the context object gives the currently applied line dash pattern.

Syntax

Following is the syntax of HTML Canvas getLineDash() method −

CanvasRenderingContext2D.getLineDash();

Parameters

This is only a return method. Hence, it does not take any parameters.

Return values

An array is returned containing the distances of drawing the line and gap used.

Example 1

The following example draws a line in the canvas element after applying line dash method and shows the variables used in the window alert of the webpage every time when loaded by the HTML Canvas getLineDash() method.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="250" height="100" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.setLineDash([5, 10]);
      window.alert(context.getLineDash());
      context.beginPath();
      context.moveTo(10, 50);
      context.lineTo(200, 50);
      context.stroke();
      context.closePath();
   </script>
</body>
</html>

Output

The output returned by the above code on the webpage as −

HTML Canvas GetLineDash Method

The output returned in the window alert as −

HTML Canvas GetLineDash Method

Example 2

The following example draws two lines and applies the line dash to them using setLineDash() method and then returns their array inputs by window alert using getLineDash() method.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="200" height="200" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.setLineDash([5, 10, 15]);
      window.alert(context.getLineDash());
      context.beginPath();
      context.moveTo(40, 50);
      context.lineTo(140, 100);
      context.lineTo(40, 150);
      context.stroke();
      context.closePath();
   </script>
</body>
</html>

Output

The output returned by the above code on the webpage as −

HTML Canvas GetLineDash Method

The output returned in the window alert as −

HTML Canvas GetLineDash Method
html_canvas_lines.htm
Advertisements