HTML5 Game - Canvas Shape Dashed Lines

Introduction

The code calculates the length of the line and, based on the length of each dash.

And it figures out how many dashes the line will contain.

Demo

ResultView the demo in separate window

<!DOCTYPE html>
   <head>
     <title>Dashed lines</title>
      <style> 
         body {//from   w ww . j  av a2  s.  c  o m
            background: #dddddd;
         }

         #canvas {
            position: absolute;
            left: 0px;
            top: 0px;
            margin: 20px;
            background: #ffffff;
            border: thin solid #aaaaaa;
         }
      </style>
   </head>

  <body>
    <canvas id='canvas' width='500' height='500'>
      Canvas not supported
    </canvas>

    <script>
let context = document.querySelector('#canvas').getContext('2d');

function drawDashedLine(context, x1, y1, x2, y2, dashLength) {
   dashLength = dashLength === undefined ? 5 : dashLength;

   let deltaX = x2 - x1;
   let deltaY = y2 - y1;
   let numDashes = Math.floor(Math.sqrt(deltaX * deltaX + deltaY * deltaY) / dashLength);

   for (let i=0; i < numDashes; ++i) {
      context[ i % 2 === 0 ? 'moveTo' : 'lineTo' ](x1 + (deltaX / numDashes) * i, y1 + (deltaY / numDashes) * i);
   }

   context.stroke();
};

context.lineWidth = 3;
context.strokeStyle = 'blue';

drawDashedLine(context, 20, 20, context.canvas.width-20, context.canvas.height);
drawDashedLine(context, context.canvas.width-20, 20, context.canvas.width-20, context.canvas.height-20, 10);
drawDashedLine(context, context.canvas.width-20, context.canvas.height-20, 20, context.canvas.height-20, 15);
drawDashedLine(context, 20, context.canvas.height-20, 20, 20, 2);

      </script>
  </body>
</html>