2013-07-21 52 views
15

我正在使用d3.js作图。在某些时候,如果数值是跨越某个边界,然后用填充图形显示该部分,则必须显示某些图形的特殊部分的数据。更清晰的是在那里和形象。用图案填充直方图

我得到了穿过边界的矩形部分,但我怎样才能用这种模式填充它? 任何CSS或画布技巧?

enter image description here

注:该图片只是一个例子不是真正的一个

+0

[在SVG简单填充图案:斜线阴影]的可能重复(http://stackoverflow.com/questions/13069446/simple-填充模式在svg对角线孵化) –

回答

20

如何:

Live Demo

JS

var svg = d3.select("body").append("svg"); 

svg 
    .append('defs') 
    .append('pattern') 
    .attr('id', 'diagonalHatch') 
    .attr('patternUnits', 'userSpaceOnUse') 
    .attr('width', 4) 
    .attr('height', 4) 
    .append('path') 
    .attr('d', 'M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2') 
    .attr('stroke', '#000000') 
    .attr('stroke-width', 1); 

svg.append("rect") 
     .attr("x", 0) 
     .attr("width", 100) 
     .attr("height", 100) 
     .style("fill", 'yellow'); 

svg.append("rect") 
    .attr("x", 0) 
    .attr("width", 100) 
    .attr("height", 100) 
    .attr('fill', 'url(#diagonalHatch)'); 

结果

enter image description here

+0

我使用模式来填充矩形,但这种模式失去了它的原始颜色我们可以保持既像填充颜色和透明模式都? –

+1

您必须复制矩形(一个使用颜色,另一个使用花样),因为您不能在同一个矩形上同时使用填充颜色和填充模式。您可能可以修改模式本身并在其中创建背景色,但这超出了我的理解。即使你可以,你也需要每种颜色都重复的图案。 –

1

要更改颜色将是简单,只是一个条件if声明。下面是我以前用过的一个例子:

svg.selectAll("dot")  
     .data(data)          
    .enter().append("circle")        
     .attr("r", 3.5)  
     .style("fill", function(d) {   // <== Add these 
      if (d.close >= 50) {return "red"} // <== Add these 
      else { return "black" }   // <== Add these 
     ;})          // <== Add these 
     .attr("cx", function(d) { return x(d.date); })  
     .attr("cy", function(d) { return y(d.close); });  

要添加的模式将是一个涉及多一点,你首先要对defs组件添加到您的SVG,然后你的模式添加到它

//first create you SVG or select it 
var svg = d3.select("#container").append("svg"); 

//then append the defs and the pattern 
svg.append("defs").append("pattern") 
    .attr("width", 5) 
    .attr("height", 5); 
+0

在这里,如果条件决定哪个矩形是它,我使用模式来填充矩形,但这种模式失去了它的原始颜色我们可以保持像填充颜色和透明模式? –

+0

我使用模式来填充矩形,但这种模式失去它的原始颜色我们可以保持既像填充颜色和透明模式都? –