HTML5 Game - Using a Linear Gradient

Introduction

A linear gradient sets the colors along a line.

The following code shows how to create a simple linear gradient.

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");
            //from   ww  w.j ava 2  s.  co m
            ctx.fillStyle = grad;
            ctx.fillRect(0, 0, 500, 140);            
        </script>
    </body>
</html>

When using the createLinearGradient method, we supply four values.

The first argument to the addColorStop method is the position on the line that we want to apply the color, which we specify using the second argument.

The start of the line (the coordinate 0, 0 in this example) is represented by the value 0 and the end of the line by the value 1.

Once we have defined the gradient and added the color stops, we can assign the CanvasGradient object to set the fillStyle or strokeStyle properties.

ctx.fillStyle = grad;  

Finally, we can draw a shape.

ctx.fillRect(0, 0, 500, 140);              

Related Topic