给定任意颜色范围,均匀分布 canvas 渐变颜色
Distribute canvas gradient colors evenly given an arbitrary color range
我正在尝试在给定随机颜色范围的情况下均匀分布 canvas
线性渐变。像这样。
let canvas = document.getElementsByTagName("CANVAS")[0];
let ctx = canvas.getContext("2d");
let gradient = ctx.createLinearGradient(0, 0, 200, 0);
// generate some random colors
let random = Math.round(Math.random() * (10 - 2) + 2)
let colors = Array.from( Array( random ).keys() ).map(function(){
return '#'+Math.floor(Math.random()*16777215).toString(16);
});
// loop through the colors and add color stop with percentage.
colors.forEach( (color, index) => {
let percentage = (index / colors.length) / 1;
console.log(percentage);
gradient.addColorStop(percentage, color);
})
ctx.fillStyle = gradient;
ctx.fillRect(10, 10, 200, 100);
这个问题是它不均匀。它不可避免地以更长的梯度结束。我如何计算渐变在矩形上的百分比。
您需要将公式更改为
let percentage = index / (colors.length - 1);
因为索引从 0
到 colors.length-1
(含)。
这样每次转换都会获得相同数量的像素。
我正在尝试在给定随机颜色范围的情况下均匀分布 canvas
线性渐变。像这样。
let canvas = document.getElementsByTagName("CANVAS")[0];
let ctx = canvas.getContext("2d");
let gradient = ctx.createLinearGradient(0, 0, 200, 0);
// generate some random colors
let random = Math.round(Math.random() * (10 - 2) + 2)
let colors = Array.from( Array( random ).keys() ).map(function(){
return '#'+Math.floor(Math.random()*16777215).toString(16);
});
// loop through the colors and add color stop with percentage.
colors.forEach( (color, index) => {
let percentage = (index / colors.length) / 1;
console.log(percentage);
gradient.addColorStop(percentage, color);
})
ctx.fillStyle = gradient;
ctx.fillRect(10, 10, 200, 100);
这个问题是它不均匀。它不可避免地以更长的梯度结束。我如何计算渐变在矩形上的百分比。
您需要将公式更改为
let percentage = index / (colors.length - 1);
因为索引从 0
到 colors.length-1
(含)。
这样每次转换都会获得相同数量的像素。