Fill rect with pattern

后端 未结 2 837
天涯浪人
天涯浪人 2020-12-31 02:28

I am using d3.js for graph. at some point i have to show data with some special part of graph for example if the values is cross some boundary then show that part with filli

相关标签:
2条回答
  • 2020-12-31 03:15

    To change the color would be simple, just a conditional if statement. Here's an example i've used before:

    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); });    
    

    To add a pattern would be a little more involved as you first have to add the defs element to your SVG and then add your pattern to it

    //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)
  • 2020-12-31 03:31

    How about this:

    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)');
    

    Results

    enter image description here

    0 讨论(0)
提交回复
热议问题