HTML5 Game - Using a Radial Gradient

Introduction

We define radial gradients using two circles.

The start of the gradient is defined by the first circle, the end of the gradient by the second circle and we add color stops between them.

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.createRadialGradient(250, 70, 20, 200, 60, 100);
            grad.addColorStop(0, "red");
            grad.addColorStop(0.5, "white");
            grad.addColorStop(1, "black");
            //ww  w  .j  av a 2  s  .c  o m
            ctx.fillStyle = grad;
            ctx.fillRect(0, 0, 500, 140);
        </script>
    </body>
</html>

The six arguments to the createRadialGradient method represent:

  • The coordinate for the center of the start circle (the first and second arguments)
  • The radius of the start circle (the third argument)
  • The coordinate for the center of the finish circle (the fourth and fifth arguments)
  • The radius of the finish circle (the sixth argument)

Related Topic