HTML5 Game - Using smaller shapes with an image pattern

Introduction

The following code shows using the pattern for smaller fill and stroke shapes.

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>
        <img id="banana" hidden src="banana-small.png"/>
        <script>
            let ctx = document.getElementById("canvas").getContext("2d");
            let imageElem = document.getElementById("banana");
            /*from  w  w w  . j a v a  2 s . c  om*/
            let pattern = ctx.createPattern(imageElem, "repeat");

            ctx.fillStyle = pattern;
            ctx.fillRect(150, 20, 75, 50);
            
            ctx.lineWidth = 8;
            ctx.strokeStyle = pattern;
            ctx.strokeRect(250, 20, 75, 50);            
        </script>
    </body>
</html>

Related Topic