圆锥形渐变的圆圈

时间:2011-06-10 14:35:53

标签: javascript raphael

是否可以创建一个带有锥形渐变的raphael圆? 像http://raphaeljs.com/picker/的色轮,但有自定义的颜色 例如:“从红色到橙色到黄色到绿色到黄色到橙色到红色”“

1 个答案:

答案 0 :(得分:4)

是的,尝试这个功能(我从拉斐尔的Colorpicker代码中获取,使其独立并在特定颜色之间添加渐变,而不是仅增加光盘上的色调):

var paper = Raphael('paper', 800, 600);

var wheel = function (x, y, r, colors) {
    var pi = Math.PI;
    var nbColors = colors.length;
    //    Formatting every color to its RGB values
    for (var i = 0 ; i < nbColors ; i++)
    {
        colors[i] = Raphael.getRGB(colors[i]);
    }
    //    Initialize segments    
    var segments = pi * r * 2 / Math.min(r / 8, 4);
    var a = pi / 2 - pi * 2 / segments * 1.5;
    var path = ["M", x, y - r, "A", r, r, 0, 0, 1, r * Math.cos(a) + x, y - r * Math.sin(a), "L", x, y, "z"].join();
    //    Draw segments
    for (var i = 0 ; i < segments ; i++)
    {
        //    Between which 2 colors is this segment?
        var j = nbColors * i / segments;
        var n = Math.floor(j);
        var d = j % 1;
        var color1 = colors[n];
        var color2 = colors[(n + 1) % nbColors];
        //    Calculate the segment's color from the 2 other
        var color =
        {   r :   Math.round(d * (color2.r - color1.r) + color1.r)
        ,   g :   Math.round(d * (color2.g - color1.g) + color1.g)
        ,   b :   Math.round(d * (color2.b - color1.b) + color1.b)
        }
        //    Draw the sector
        paper.path(path).attr(
        {   stroke: 'none'
        ,   fill: 'rgb(' + color.r + ',' + color.g + ',' + color.b + ')'
        ,   rotation: [90 + (360 / segments) * i, x, y]
        });
    }
    //    Surrounding circle
    return paper.circle(x, y, r).attr(
    {   stroke : '#fff'
    ,   'stroke-width' : Math.round(r * .03)
    });
};

您可以像这样使用它,第4个参数是要使用的颜色数组:

wheel (100, 100, 50, ['#F00', '#0FF', '#00F', '#0F0', '#F80']);
wheel (500, 200, 50, ['rgb(255,0,0)', 'hsb(40,100,100)', '#0F00F0']);