Sinful17 Sinful17 - 1 year ago 57
jQuery Question

drawing a rainbow with canvas and javascript

Hello everyone I am trying to draw a simple rainbow in canvas by using half circles. My first circle was created an worked perfectly.

<!DOCTYPE html>

<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #000000;">

var omkadering = document.getElementById("myCanvas");
var context = omkadering.getContext("2d");

context.lineWidth = 10;
context.strokeStyle = "violet";


this actually worked fine I had the first layer done
first layer

then I tried to make the second one so I added this part

context.strokeStyle = "violet";
-- started new code here --
context.strokeStyle = "indigo";
-- new code ends here --


but it overwrites the old layer

layer 2 result

I tried several other methods too, like making a new variable context or separating them from each other but none helped

does anyone had an idea what I do wrong or forgot to add ?

thanks in advance !

Ian Dessers

Answer Source

You can also create a rainbow with a radial gradient:

enter image description here

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var cx=cw/2;
var cy=ch/2;


function draw() {
  var gradient = ctx.createRadialGradient(cx,ch,50,cx,ch,100);
  var stop=1/8;
  gradient.addColorStop(stop*0, 'transparent');
  gradient.addColorStop(stop*1, 'red');
  gradient.addColorStop(stop*2, 'orange');
  gradient.addColorStop(stop*3, 'yellow');
  gradient.addColorStop(stop*4, 'green')
  gradient.addColorStop(stop*5, 'blue');
  gradient.addColorStop(stop*6, 'Indigo');
  gradient.addColorStop(stop*7, 'violet');
  gradient.addColorStop(stop*8, 'transparent');
  ctx.fillStyle = gradient;
body{ background-color:white; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=125></canvas>