2015-06-20 385 views

回答

3

這裏有一個快速d3實現:

<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <script data-require="[email protected]" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script> 
 
</head> 
 

 
<body> 
 
    <script> 
 
    var data = [{ 
 
     color: 'white', 
 
     label: 'Snow' 
 
    }, { 
 
     color: 'red', 
 
     label: 'Rock' 
 
    }, { 
 
     color: 'purple', 
 
     label: 'Pine' 
 
    }, { 
 
     color: 'blue', 
 
     label: 'Basalt' 
 
    }, { 
 
     color: 'lightblue', 
 
     label: 'Dog' 
 
    }, { 
 
     color: 'green', 
 
     label: 'Cat' 
 
    }, { 
 
     color: 'yellow', 
 
     label: 'Lava' 
 
    }, { 
 
     color: 'orange', 
 
     label: 'Fish' 
 
    }, { 
 
     color: 'black', 
 
     label: 'Sand' 
 
    }] 
 

 
    var width = 500, 
 
     height = 150; 
 

 
    var svg = d3.select('body') 
 
     .append('svg') 
 
     .attr('width', 500) 
 
     .attr('height', height); 
 

 
    var grad = svg.append('defs') 
 
     .append('linearGradient') 
 
     .attr('id', 'grad') 
 
     .attr('x1', '0%') 
 
     .attr('x2', '100%') 
 
     .attr('y1', '0%') 
 
     .attr('y2', '0%'); 
 

 
    grad.selectAll('stop') 
 
     .data(data) 
 
     .enter() 
 
     .append('stop') 
 
     .attr('offset', function(d, i) { 
 
     return (i/data.length) * 100 + '%'; 
 
     }) 
 
     .style('stop-color', function(d) { 
 
     return d.color; 
 
     }) 
 
     .style('stop-opacity', 0.9); 
 

 
    svg.append('rect') 
 
     .attr('x', 0) 
 
     .attr('y', 0) 
 
     .attr('width', 500) 
 
     .attr('height', height/2) 
 
     .attr('fill', 'url(#grad)'); 
 
     
 
    var g = svg.append('g') 
 
     .selectAll('.label') 
 
     .data(data) 
 
     .enter(); 
 
    
 
    g.append('line') 
 
     .style('stroke', function(d) { 
 
     return d.color; 
 
     }) 
 
     .style('stroke-width', 2) 
 
     .attr('x1',function(d,i){ 
 
     return xPos(i) 
 
     }) 
 
     .attr('x2',function(d,i){ 
 
     return xPos(i) 
 
     }) 
 
     .attr('y1',function(d,i){ 
 
     return height/2; 
 
     }) 
 
     .attr('y2',function(d,i){ 
 
     return height 
 
     }); 
 
     
 
     
 
    g.append('text') 
 
     .text(function(d){ 
 
     return d.label; 
 
     }) 
 
     .attr('transform',function(d,i){ 
 
     return 'translate(' + (xPos(i) + 2) + ',' + ((height) - 7) + ')'; 
 
     }) 
 
     
 
    function xPos(i){ 
 
     return (width/data.length) * i; 
 
    } 
 
     
 
    </script> 
 
</body> 
 

 
</html>

Plnkr例here