HTML5 Game - Setting the Fill and Stroke Styles

Introduction

When setting a style using the fillStyle or strokeStyle properties, we can specify a color using the CSS color values via either a name or a color model.

The following code shows how to set colors using the fillStyle and strokeStyle properties.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <style>
            canvas {border: thin solid black; margin: 4px}
        </style>
    </head>
    <body>
        <canvas id="canvas" width="500" height="140">
            Your browser doesn't support the <code>canvas</code> element
        </canvas>
        <script>
            let ctx = document.getElementById("canvas").getContext("2d");
            /*from  www  . j a v  a2s.c  o m*/
            let offset = 10;
            let size = 50;
            let count = 5;
            ctx.lineWidth = 3;            
            let fillColors = ["black", "grey", "lightgrey", "red", "blue"];
            let strokeColors = ["rgb(0,0,0)", "rgb(100, 100, 100)",
                                "rgb(200, 200, 200)", "rgb(255, 0, 0)",
                                "rgb(0, 0, 255)"];

            for (let i = 0; i < count; i++) {
                ctx.fillStyle = fillColors[i];
                ctx.strokeStyle = strokeColors[i];
                
                ctx.fillRect(i * (offset + size) + offset, offset, size, size);
                ctx.strokeRect(i * (offset + size) + offset, (2 * offset) + size,
                               size, size);                
            }
        </script>
    </body>
</html>

In this example, I define two arrays of colors using the CSS color names and the rgb model.

The these colors was set to the fillStyle and strokeStyle properties in the for loop which calls the fillRect and strokeRect methods.

Related Topic