Create a Rainbow with HTML5 Gradients

Introduction

Learn to create stunning rainbows for Web pages.
You don't need photographs of rainbows. Accomplish everything with HTML5.
Tap an image from rainbow examples above.
Apply HTML5 with radial gradients.
If you're unfamiliar with radial gradients
see the introduction to radial gradients
tutorial.
This tutorial builds on the
introduction to radial gradients.
Learn to prepare a simple rainbow with gradients.
See the natural rainbow tutorial
to apply masks and transparency over a photograph for more advanced effects.

Generate the Rainbow Effect

The rainbow effect was generated with
colors of the rainbow as they appear in order.
However the
Rainbow on Blue Example
doesn't include indigo.
Create a
full circle radial gradient.
Stop colors fade
from the background color, to red, yellow, and blue,
then back to the background color.

The following listing demonstrates
creating a radial gradient which
resembles a rainbow.
Parameter sBg
equals "rgba(5,5,141,".
The base color for most color stops
has a red channel of 5,
a green channel of 5,
and a blue channel of 141.
The following listing demonstrates
adding the alpha value to a set of
rgba color stops.
Color stops are also declared
with Hexadecimal Colors.

Translate the canvas to
move the rainbow gradient toward the right
and down.
Moving the radial gradient, effectively
crops the bottom and right side.
Variable N_DIM equals
the width and height of the canvas.

Tips

Include
the full range of colors
if you want to represent a rainbow or prism with more accuracy.
Gently fade from
one color to the next.
Select colors with an image editing application such as Photoshop.
However red, yellow, and green appear
to occupy more area within a rainbow in photographs.
It can be a little tricky to
modify the appearance
of color transitions precisely.

Experiment with radial gradients for
an amazing variety of effects.
Try various colors, stops,
and settings, to discover new effects.
The examples below
were generated with radial gradients.

Perhaps the most compelling effects are generated
with animated gradients.
However be careful. Minimize the number of radial gradients.
Mobile
devices may slow down when processing many
animated
gradients.

Reuse Code

Code reuse can decrease development and debugging time.
It usually takes less time and effort to prepare some code
that works well, then use the code in other projects.
The
drawRainbow() function
works for both the simple
rainbow
and the
rainbow over a landscape examples.

Summary

This tutorial explained how to create stunning rainbows for Web pages.
You don't need photographs of rainbows. Accomplish everything with HTML5.
Tap an image above
to see beautiful rainbow examples.
Apply HTML5 with radial gradients.
See the
Rainbow Effect Source Code
for details.