Search This Blog

draw dashed line on HTML 5 canvas




Click to see the example






  • Javascript source code:
    function drawDashedLine(context, fromX, fromY, toX, toY, dashPattern) {
     
     context.beginPath();
     
     var dx = toX - fromX;
     var dy = toY - fromY;
     var angle = Math.atan2(dy, dx);
     var x = fromX;
     var y = fromY;
     context.moveTo(fromX, fromY);
     var idx = 0;
     var draw = true;
     while (!((dx < 0 ? x <= toX : x >= toX) && (dy < 0 ? y <= toY : y >= toY))) {
      var dashLength = dashPattern[idx++ % dashPattern.length];
      var nx = x + (Math.cos(angle) * dashLength);
      x = dx < 0 ? Math.max(toX, nx) : Math.min(toX, nx);
      var ny = y + (Math.sin(angle) * dashLength);
      y = dy < 0 ? Math.max(toY, ny) : Math.min(toY, ny);
      if (draw) {
       context.lineTo(x, y);
      } else {
       context.moveTo(x, y);
      }
      draw = !draw;
     }
     
     context.closePath();
     context.stroke();
    };
    function drawDashedLineOnCanvas(){
        var canvas = document.getElementById("htmlCanvas");
        var context = canvas.getContext("2d");
        context.strokeStyle="#ff0000";
        context.lineCap = "round";
        context.lineWidth = 1;
        drawDashedLine(context, 0, 0, 0,100,[5,10]);
        drawDashedLine(context, 0, 100, 100,100,[5,10]);
        drawDashedLine(context, 100, 100, 100,0,[5,10]);
        drawDashedLine(context, 100, 0, 0,0,[5,10]);
        drawDashedLine(context, 0, 0, 100,100,[5,10]);
    };
    
  • html source code:
    <div style="border: 3px coral solid;" onClick="drawDashedLineOnCanvas();">
    <p>Click to see the example</p>
    <canvas id="htmlCanvas" width="100%" height="300"></canvas>
    </div>
    

See also

No comments:

Post a Comment