// returns an array of CSS color strings
// @from: CSS color string of first color
// @to: CSS color string of last color
// @numberOfShades: number of shades to be returned (from and end included)
function getGradColors(from, to, numberOfShades){
// generate a canvas context and store it in cache
var ctx = getGradColors.ctx || (getGradColors.ctx = document.createElement('canvas').getContext('2d'));
// set our canvas dimensions according to the number of shades required
var w = ctx.canvas.width = numberOfShades || 10;
ctx.canvas.height = 1;
// create a linear gradient
// (to keep 'from' and 'to' values, we set its x to 1 and width to width -1)
var grad = ctx.createLinearGradient(1,0,w-1, 0);
grad.addColorStop(0, from || 'white');
grad.addColorStop(1, to || 'black');
ctx.fillStyle = grad;
ctx.fillRect(0,0,w,1); // draw it
var data = ctx.getImageData(0,0,w,1); // get the pixels info ([r, g, b, a, r, g...])
var colors = [];
data.data.forEach(function(comp, i){
if(i%4===0){ // map each pixel in its own array
colors.push([]);
}
if(i%4===3){ // alpha
comp /= 255;
}
colors[colors.length - 1].push(comp);
});
return colors.map(function(c){
// return a CSS computed value
ctx.fillStyle = 'rgba('+c.join()+')';
return ctx.fillStyle;
});
}
var shadesOfWhite = getGradColors('#f25f9a', 'white', 10);
console.log('to white: ', shadesOfWhite);
shadesOfWhite.forEach(generateSpan);
container.appendChild(document.createElement('br'));
var shadesOfBlack = getGradColors('#f25f9a', 'black', 10);
console.log('to black: ', shadesOfBlack);
shadesOfBlack.forEach(generateSpan);
function generateSpan(color){
var span = document.createElement('span');
span.style.backgroundColor = color;
container.appendChild(span);
}
#container > span{
width: 10vw;
height: 5vw;
display: inline-block;
}
body{margin: 0}
<div id="container"></div>
您所選擇的顏色看起來像#COLOR一個線性漸變爲白色,這是你想要的嗎? – Kaiido
對不起,我忘了鏈接,這裏是一個很好的例子:http://www.color-hex.com/color/f25f9a。 – jon
顏色是3D空間中的點。如果要生成隨機的「相似」顏色,請在三維空間中選擇(a)在給定點附近的隨機點,(b)在某個座標系的某條線上與該點共線。 –