我有一个小功能可以为 HTML5 Canvas 线性和/或径向渐变方法创建随机颜色停止...
HTML
<canvas id="cnv" width="300" height="200"></canvas>
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();
函数randomColorStops() 接受一个数字作为参数(这里通过nos() 随机生成)并返回一个有序对象数组,每个对象都有一个“停止”和“颜色”属性。然后将其迭代并添加到梯度变量 (grad)。
它可能对某人有用
请参阅jsFiddle of the above code。