web-dev-qa-db-ja.com

長方形をパターンで塗りつぶす

グラフにd3.jsを使用しています。ある時点で、グラフの特別な部分でデータを表示する必要があります。たとえば、値が境界を越えている場合は、その部分を塗りつぶしパターンで表示します。より明確にするために、画像があります。

境界を越える長方形の部分を取得しますが、どうすればこのパターンで塗りつぶすことができますか? cssまたはcanvasのトリックはありますか?

enter image description here

注:この画像は単なる例であり、実際の画像ではありません

15
Amit Rana

これはどう:

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

21
Brandon Boone

色を変更するのは簡単で、条件付きの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);
1
Kevin Lynch