JSFiddle - React, Tailwind, and code Playground
by B L Praveen
HTML
<canvas id="canvas" width=250 height=250></canvas>
JavaScript
renderGradient();
function renderGradient() {
var color, colors, gradient, index, xy, _i, _len, _ref, _ref1;
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
renderSpectrum();
// supply the proper position/radius here:
var square = getSquareInCircle(canvas.width/2, canvas.height/2, canvas.width * 0.8);
gradient = ctx.createLinearGradient(0, 0, -6, canvas.width * 0.8);
gradient.addColorStop(0,'#000');
gradient.addColorStop(1,'#000');
ctx.fillStyle = gradient;
return ctx.fillRect(square,x, square.y, square.w, square.h);
//return ctx.fillRect(p_side, p_side, width, width);
};
function renderSpectrum() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var radius = canvas.width / 2;
var toRad = (2 * Math.PI) / 360;
var step = 1 / radius;
ctx.clearRect(0, 0, canvas.width, canvas.height);
for(var i = 0; i < 360; i += step) {
var rad = i * toRad;
ctx.strokeStyle = 'hsl(' + i + ', 100%, 50%)';
ctx.beginPath();
ctx.moveTo(radius, radius);
ctx.lineTo(radius + radius * Math.cos(rad), radius + radius * Math.sin(rad));
ctx.stroke();
}
ctx.fillStyle = 'rgb(255, 255, 255)';
ctx.beginPath();
ctx.arc(radius, radius, radius * 0.8, 0, Math.PI * 2, true);
ctx.closePath();
return ctx.fill();
}
function getSquareInCircle(cx, cy, radius) {
var side = Math.sqrt(radius * radius * 2), // calc side length of square
half = side * 0.5; // position offset
return {
x: cx - half,
y: cy - half,
w: side,
h: side
}
}