2011-08-28 107 views
4

我有一個顏色列表(created from values),並希望在顏色欄中顯示它們(作爲圖例每種顏色的含義)。像這樣的東西。Javascript colorbar - 創建它的最佳方法

Example for a colour bar

的一種方法是用1行/ N列(N = 25-100),代表一個顏色的每個列的表。有沒有更好的方法來做到這一點?

+0

使用圖像,比表格更好。鼠標指針懸停在圖像上的位置將決定你正在處理的顏色。 – yoda

+0

我需要動態創建圖像。我有動態創建的顏色表。 –

回答

5

畫布是一個功能強大的API: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

非常好!而已! –

+0

@霍斯特沃爾特:這很好,只是忘了提及IE8不支持這一點,這可能很重要。 – pimvdb

+0

是的,很高興知道,但在我的用例中不相關。謝謝, –