HTML5 Canvas : Random Color Stops
The function randomColorStops() takes a number as an argument (here generated randomly via nos()) and returns an array of ordered objects, each with a 'stops' and 'color' property. This is then iterated and added to the gradient variable (grad).
http://stackoverflow.com/a/38860408/4746328
by Brian Peacock
August 09, 2016
HTML
<h3>
Random ColorStops for HTML5 Canvas
</h3>
<canvas id="cnv" width="300" height="200"></canvas>
CSS
canvas {
width:300px;
height:200px;
border:1px solid #999;
margin:24px auto;
clear:both;
display:block;
}
h3 {
text-align:center;
}
JavaScript
/* simple selection */
var $ = function(a) {return document.getElementById(a.slice(1));};
var randomColorStops = function(num) {
var arr = [];
var stops = [];
var L = num;
var obj;
var randomRGB = function() {
var colorValue = function() {
return Math.floor(Math.random() * 255);
};
return 'rgb('+colorValue()+','+colorValue()+','+colorValue()+')';
};
while(L--) {
arr.push(
parseFloat(
(Math.random()).toFixed(2)
)
);
}
arr.sort();
L = num;
while(L--) {
obj = {
stop: arr[L],
color: randomRGB()
};
stops.push(obj);
}
return stops;
}
/* canvas properties */
var canvas = $('#cnv');
var ctx = canvas.getContext('2d');
var cx = canvas.width / 2;
var cy = canvas.height / 2;
var cr = canvas.height * 0.45;
/* number of stops: random number 5-50 */
var nos = function() {
return Math.floor(Math.random() * 45) + 5;
};
/* create radial gradient */
var grad = ctx.createRadialGradient(
cx - (cr * 0.33),
cy - (cr * 0.33),
2,
cx - (cr * 0.33),
cy - (cr * 0.33),
cr * 1.66
);
/* !!! stops = random number of random colour-stops */
var stops = randomColorStops(nos());
var len = stops.length;
/* iterate stops and add to grad */
for (var i = 0; i < len; i++) {
grad.addColorStop(stops[i].stop, stops[i].color);
}
/* draw to canvas */
/* background: black */
ctx.fillStyle = '#000';
ctx.beginPath();
ctx.fillRect(0, 0, canvas.width, canvas.height);
/* circle: random gradient */
ctx.fillStyle = grad;
ctx.beginPath();
ctx.arc(cx, cy, cr, 0, Math.PI*2, true);
ctx.fill();