开发者

Javascript colorbar - best way to create it

开发者 https://www.devze.com 2023-03-31 20:18 出处:网络
I have a list of colours (created from values) and want to display them in a colourbar (as a legend what each colour means). Something like this.

I have a list of colours (created from values) and want to display them in a colourbar (as a legend what each colour means). Something like this.

Javascript colorbar - best way to create it

One way would be a table with 1 row / n columns (n = 25-100), ea开发者_运维知识库ch column representing one colour. Is there any better way to do this?


Canvas is a powerful API for this: http://jsfiddle.net/pimvdb/eGjak/89/.

var cv  = document.getElementById('cv'),
    ctx = cv.getContext('2d');

for(var i = 0; i <= 255; i++) { // fill strokes
    ctx.beginPath();

    var color = 'rgb(100, ' + i + ', ' + i + ')';
    ctx.fillStyle = color;

    ctx.fillRect(i * 2, 0, 2, 50);
}

cv.onclick = function(e) {
    var x = e.offsetX, // mouse x
        y = e.offsetY, // mouse y
        p = ctx.getImageData(x, y, 1, 1),
        x = p.data; // pixel at mouse (x, y) - contains [r, g, b, a]

    alert('Color: rgb(' + x[0] + ', ' + x[1] + ', ' + x[2] + ')');
};
0

精彩评论

暂无评论...
验证码 换一张
取 消