HTML5 Game - Canvas Shape Zigzag

Introduction

The following code shows how to draw path by iteratively connecting line subpaths to draw a zigzag path.

Demo

ResultView the demo in separate window

<html>
    <head>
        <script> 
            window.onload = function(){
                let canvas = document.getElementById("myCanvas");
                let context = canvas.getContext("2d");
        /*  w ww. j  a va  2  s. c o  m*/
                let startX = 85;
                let startY = 70;
                let zigzagSpacing = 60;
                
                context.lineWidth = 10;
                context.strokeStyle = "#0096FF";
                context.beginPath();
                context.moveTo(startX, startY);
                
                for (let n = 0; n < 10; n++) {
                    let x = startX + ((n + 1) * zigzagSpacing);
                    let y;
                    
                    if (n % 2 == 0) { // if n is even...
                        y = startY + 100;
                    }
                    else { // if n is odd...
                        y = startY;
                    }
                    context.lineTo(x, y);
                }

                context.stroke();
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Note

To draw a zigzag, connect alternating diagonal lines to form a path.

The beginPath() method starts a path.

Without using the beginPath() method, we have to position the canvas context using moveTo() for each line segment.

The line join style of the HTML5 canvas path is defaulted to miter.

Alternatively, we can set the line join style to round or bevel with the lineJoin property.