Sinful17 Sinful17 - 6 months ago 21
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>
<html>
<body>

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

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

context.beginPath();`
context.arc(95,100,80,3.1,2*Math.PI);
context.lineWidth = 10;
context.strokeStyle = "violet";
context.stroke();

</script>
</body>
</html>


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.closePath();
context.beginPath();
context.arc(95,120,80,3.1,2*Math.PI);
context.strokeStyle = "indigo";
-- new code ends here --
context.stroke();

</script>
</body>
</html>


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

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;

draw();

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;
  ctx.fillRect(0,0,cw,ch);
  ctx.fill();
}
body{ background-color:white; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=125></canvas>