HTML5 Game - Using a Linear Gradient with a Smaller Shape

Introduction

When we define the gradient line, we do so relative to the canvas, not the shapes that we draw.

The following code shows a gradient with a shape that doesn't fill the canvas.

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");

            let grad = ctx.createLinearGradient(0, 0, 500, 140);
            grad.addColorStop(0, "red");
            grad.addColorStop(0.5, "white");
            grad.addColorStop(1, "black");
            /*  ww  w  .java2 s .  com*/
            ctx.fillStyle = grad;
            ctx.fillRect(10, 10, 50, 50);            
        </script>
    </body>
</html>

Related Topic