HTML Canvas Line Zig zag

Description

HTML Canvas Line Zig zag

View in separate window


<html>
    <head>
        <script> 
            window.onload = function(){
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");
        //from w  w w .  j a v a 2  s. c  o  m
                var startX = 80;
                var startY = 70;
                var zigzagSpacing = 50;
                
                context.lineWidth = 10;
                context.strokeStyle = "red"; 
                context.beginPath();
                context.moveTo(startX, startY);
                
                for (var n = 0; n < 10; n++) {
                    var x = startX + ((n + 1) * zigzagSpacing);
                    var 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>



PreviousNext

Related