Search code examples
javascriptcsssvgd3.js

Fill rect with pattern


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 filling pattern. for more clear is there in and image.

i get the rect part that cross the boundary but how can i fill it with this pattern? any css or canvas tricks?

enter image description here

Note : this image is just an example not the real one


Solution

  • 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