多色/非均匀渐变

时间:2016-08-08 19:47:30

标签: canvas html5-canvas processing p5.js

想要创建像这样的渐变效果html画布或处理。多彩/不均匀,有点随机。我的第一个倾向是创建几个点,为它们分配颜色和重量,然后通过每个点的1 / R ^ 2函数在画布上插入每个像素颜色?

绝对对其他建议持开放态度。谢谢! enter image description here

1 个答案:

答案 0 :(得分:0)

我有一个小功能来为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()随机生成)并返回一个有序对象数组,每个对象都带有一个&#39; stop&#39;和&#39;颜色&#39;属性。然后迭代并将其添加到梯度变量(grad)。

对某人dunno??

可能有用

请参阅jsFiddle of the above code