【问题标题】:Distribute canvas gradient colors evenly given an arbitrary color range在给定任意颜色范围的情况下均匀分布画布渐变颜色
【发布时间】:2019-11-04 17:00:05
【问题描述】:

我正在尝试在给定随机颜色范围的情况下均匀分布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);

这个问题是它不均匀。它最终不可避免地会以更长的梯度结束。如何计算渐变在矩形中的百分比。

【问题讨论】:

    标签: html math canvas gradient linear-gradients


    【解决方案1】:

    您需要将公式更改为

    let percentage = index / (colors.length - 1);
    

    因为索引从 0 变为 colors.length-1(含)。

    这样每个过渡都会获得相同数量的像素。

    【讨论】:

    • 我确实尝试过,但它给了我渐变的中心而不是结束(或 colorStop)。我需要以某种方式减去颜色的宽度,但我不知道该怎么做。
    • 例如,如果我的数组中有三种颜色,那么您的数学运算会给我[0, .5, 1],但我需要的是[.33, .66, .99]
    • @Pardonner 要制作 3 种颜色的均匀分布的渐变,您确实需要 0、0.5、1。您的 .33 .66。 99 将创建从 0 到 0.33 和从 0.99 到 1 的纯色
    • 啊,是的。我再次查看这个问题,我的问题是我的 fillRect 宽度是 150,而我的实际渐变宽度是 200。这就是为什么我的渐变看起来都不正确的原因。感谢您加入@Kaiido
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    • 1970-01-01
    • 2020-05-14
    • 2018-03-16
    相关资源
    最近更新 更多