How can I generate a rainbow circle using HTML5 canvas?

This is not perfect (due to drawing steps …), but it can help you :

http://jsfiddle.net/afkLY/2/

HTML:

<canvas id="colors" width="200" height="200"></canvas>

Javascript:

var canvas = document.getElementById("colors");
var graphics = canvas.getContext("2d");

var CX = canvas.width / 2,
    CY = canvas.height/ 2,
    sx = CX,
    sy = CY;

for(var i = 0; i < 360; i+=0.1){
    var rad = i * (2*Math.PI) / 360;
    graphics.strokeStyle = "hsla("+i+", 100%, 50%, 1.0)";   
    graphics.beginPath();
    graphics.moveTo(CX, CY);
    graphics.lineTo(CX + sx * Math.cos(rad), CY + sy * Math.sin(rad));
    graphics.stroke();
}

The idea is to draw the disc line by line with a hue value corresponding to the line direction.

You can change the color base rotation by adding a radius angle to rad variable (adding -pi/2 to rad would make the gradient look like your figure).

EDIT: I made a new demo that generalizes the concept a bit and renders a rainbow polygon. Here is the CodePen. To get rid of the small voids beteween the colors, I used quads that overflow to the next color part, except for the last one.

Leave a Comment