-1

I'm fairly new to javascript and I want to make a small line spectrum using html canvas and javascript so that I can later animate it when a button is clicked to show absorbtion lines and such just like in chemistry. I'm just not sure if pure javascript is able to handle this. Can anyone provide some information on how this could be done or if this is even possible? I can gladly provide more information if needed.

EDIT: Here is what I have so far but I don't know why the color gradient is slanting where the colors change and the widths of the colors need adjusted so they take up equal amounts along the rectangle.

HTML

<canvas id="spectralCanvas" width="600" height="100"></canvas>

JavaScript

function loadSpectralCanvas() {
var spectralCanvas = document.getElementById('spectralCanvas');
var spectralCtx = spectralCanvas.getContext('2d');
var backgroundCtx = spectralCanvas.getContext('2d');
spectralCtx.rect(0, 0, spectralCanvas.width, spectralCanvas.height / 2);

//Creates black underlay to represent absorption lines on the spectrum.
backgroundCtx.fillStyle = 'black';
backgroundCtx.fillRect(0, 0, spectralCanvas.width, spectralCanvas.height / 2);

//Creates the ROY G BIV line spectrum.
var gradient = spectralCtx.createLinearGradient(0, 0, spectralCanvas.width, spectralCanvas.height / 2);
gradient.addColorStop(0.14, '#882022'); //Red
gradient.addColorStop(0.28, '#E83B23'); //Orange
gradient.addColorStop(0.42, '#FFF101'); //Yellow
gradient.addColorStop(0.56, '#89C540'); //Green
gradient.addColorStop(0.70, '#1BBDC9'); //Blue
gradient.addColorStop(0.84, '#0279B9'); //Indigo
gradient.addColorStop(1.0, '#58235E'); //Violet
spectralCtx.fillStyle = gradient;
spectralCtx.fill();

}

loadSpectralCanvas();

JSFiddle

user3786596
  • 117
  • 1
  • 2
  • 13

2 Answers2

0

It's definitely possible with pure JavaScript. The Mozilla Developer Network is a great resource to start with. They have a canvas tutorial that should be able to get you started in the right direction. Depending on how much experience you have you might consider going straight to the drawing shapes part of the tutorial. Good luck.

Jared Neil
  • 366
  • 3
  • 7
  • Thanks for the response. I will definately check this out. I have some code already written up with kind of what I want but the linear gradient I made is slanting the colors for some reason and the spacing needs adjusted. – user3786596 Jun 28 '14 at 22:15
0

The last argument to the create gradient function should be 0, as this will produce a horizontal gradient that stretches the width of the canvas.

For your colour stops, you may be better off writing 1/7, 2/7 and so on to let JavaScript handle it for you.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592