HTML Canvas - linedashOffset Property



The HTML Canvas lineDashOffset property of Canvas API can be used set the line dash style using an number value breaks.

This property should be applied before drawing the line and is from the CanvasRenderingContext2D interface.

Possible input values

It accepts float number values which specifies the correct space for line dash offset. The default value is taken as '0'.

Example

The following program implements the HTML Canvas lineDashOffset property to the CanvasRenderingContext2D interface context object so that a line pattern can be drawn.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="300" height="150" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.setLineDash([5, 16]);
      context.beginPath();
      context.lineWidth = 10;
      context.moveTo(0, 50);
      context.lineTo(300, 50);
      context.stroke();
      context.closePath();
      context.beginPath();
      context.strokeStyle = 'rgba(123,124,125,0.6)';
      context.lineWidth = 10;
      context.lineDashOffset = 5;
      context.moveTo(0, 100);
      context.lineTo(300, 100);
      context.stroke();
      context.closePath();
   </script>
</body>
</html>

Output

The output returned by the above code on the web page according to the pixels is −

HTML Canvas LinedashOffset Property

Example

The following program implements uses the property lineDashOffset to draw a pattern using lines and the property.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="350" height="200" style="border: 1px solid black;"></canvas>
   <script>
      function linestyles() {
         var canvas = document.getElementById("canvas");
         var ctx = canvas.getContext('2d');
         var offset = 0;
         function draw() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.setLineDash([50, 10]);
            ctx.lineDashOffset = offset;
            ctx.strokeRect(10, 10, 250, 125);
         }
         function animate() {
            offset++;
            if (offset > 25) {
               offset = 0;
            }
            draw();
            setTimeout(animate, 50);
         }
         animate();
      }
      linestyles();
   </script>
</body>
</html>

Output

The output returned by the above code on the web page according to the pixels is −

HTML Canvas LinedashOffset Property
html_canvas_lines.htm
Advertisements