HTML5 Game - Creating patterns with loops

Introduction

The following code creates a pattern with loops.

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  av a  2  s.co m*/
                let centerX = canvas.width / 2;
                let centerY = canvas.height / 2;
                
                let outerRadius = 95;
                
                let innerRadius = 50;
                
                let midRadius = innerRadius * 1.6;
                
                let holeRadius = 10;
                
                let numPoints = 50;
                
                context.beginPath();
                context.lineJoin = "bevel";
                
                for (let n = 0; n < numPoints; n++) {
                    let radius = null;
                    
                    if (n % 2 == 0) {
                        radius = outerRadius;
                    }
                    else {
                        radius = innerRadius;
                    }
                    
                    let theta = ((Math.PI * 2) / numPoints) * (n + 1);
                    let x = (radius * Math.sin(theta)) + centerX;
                    let y = (radius * Math.cos(theta)) + centerY;
                    
                    if (n == 0) {
                        context.moveTo(x, y);
                    }
                    else {
                        context.lineTo(x, y);
                    }
                }
                
                context.closePath();
                
                context.lineWidth = 5;
                context.strokeStyle = "red";
                context.stroke();
                
                
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Related Topic