HTML5 Game - Canvas Shape Polygon

Drawing Multi-Sided Shapes

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>

<head>
    <script>
        //Draws a multi-sided shape on a canvas.
        window.onload = function() {
            canvas = document.getElementById("canvasArea");
            context = canvas.getContext("2d");

            //ATTRIBUTES of shapes.
            context.strokeStyle = "black";
            context.lineWidth = 4;//w ww .j a  v a 2 s.  com
            context.lineCap = "round"
            context.shadowOffsetX = 3;
            context.shadowOffsetY = 3;
            context.shadowBlur = 5;
            context.shadowColor = "gray";

            //SHAPE 1.
            let xPos = 50;
            let yPos = 40;
            let fLength = 20;
            let cLength = 2;
            let color = "blue"
            drawShape(xPos, yPos, fLength, cLength, color);

            //SHAPE 2.
            xPos = 150;
            yPos = 40;
            fLength = 20;
            cLength = 4;
            color = "green"
            drawShape(xPos, yPos, fLength, cLength, color);

            //SHAPE 3.
            xPos = 100;
            yPos = 125;
            fLength = 20;
            cLength = .5;
            color = "purple"
            drawShape(xPos, yPos, fLength, cLength, color);

            //DRAW shape function.
            function drawShape(xPos, yPos, fLength, cLength, color) {
                //CALCULATE short length.
                let sLength = fLength / cLength;

                //PATH segments.
                context.beginPath();
                context.moveTo(xPos - (sLength), yPos - (fLength));
                context.lineTo(xPos + (sLength), yPos - (fLength));
                context.lineTo(xPos + (fLength), yPos - (sLength));
                context.lineTo(xPos + (fLength), yPos + (sLength));
                context.lineTo(xPos + (sLength), yPos + (fLength));
                context.lineTo(xPos - (sLength), yPos + (fLength));
                context.lineTo(xPos - (fLength), yPos + (sLength));
                context.lineTo(xPos - (fLength), yPos - (sLength));
                context.lineTo(xPos - (sLength), yPos - (fLength));

                //DRAW shape.
                context.fillStyle = color;
                context.fill();
                context.stroke();
            }
        }
    </script>
</head>

<body>

    <div style="width:200px;   height:200px;
                 margin:0 auto; padding:5px;">
        <canvas id="canvasArea" width="200" height="200" style="border:2px solid black">
            Your browser doesn't currently support HTML5 Canvas.
        </canvas>
    </div>
</body>

</html>

Related Topics