How to remove dashed line from HTML context

10,110

Solution 1

Wrap your code inside context.save / context.restore

ctx.save();
ctx.setLineDash([5]);
// draw dashed stuff
ctx.restore();

// now the default solid line is restored

Solution 2

You can pass empty array. It also makes line solid.

ctx.setLineDash([])

const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");

ctx.setLineDash([5, 3]);
ctx.strokeRect(20, 20, 150, 100);


button.onclick = () => {
  ctx.clearRect(15, 15, 200, 200);
  ctx.setLineDash([]);
  ctx.strokeRect(20, 20, 150, 100);
}
<!DOCTYPE html>
<html>

<body>

  <button id='button'>Unset Dashed Line</button><br>
  <canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>


</body>

</html>

Solution 3

I will try to explain as simple as I can:

enter image description here

Share:
10,110

Related videos on Youtube

MobileCushion
Author by

MobileCushion

Updated on September 15, 2022

Comments

  • MobileCushion
    MobileCushion over 1 year

    To draw a dashed line in a canvas context, I use this

        var canvas = document.getElementById('canv');
        ctx = canvas.getContext('2d');        
        ctx.setLineDash([5]);
    

    When I don't want to draw more dashed lines I do this.

        ctx.setLineDash([0]);
    

    Removing the dashs works in desktop browsers, but this is not working in mobile Safari. Is there another way to remove the dashes and draw plain continious solid lines?

    Thanks

  • Paulo Bueno
    Paulo Bueno over 8 years
    It may work, but it's not always pratical to wrap it in more complex algorithms. So would indeed choose @Denis-kreshikhin answer.
  • markE
    markE over 8 years
    @PauloBueno. I agree. At the time of my answer I didn't know that [] would clear the dashes -- or maybe that option was not available in the year before Denis's answer. Anyway, If there is no design reason to .save/.restore the canvas state I would now use [] to clear the dashes. Thanks for the heads up. :-)