Simple way to use existing object as a clipping path?

前端 未结 1 1027
不知归路
不知归路 2020-12-21 07:53

I have the following simple example, When the line extends outside the rectangle, I want to clip it. I already have the rectangle used as an outline, what is a simple way t

相关标签:
1条回答
  • 2020-12-21 08:47

    You can't reference the rectangle directly in the clip-path property, you need to create a <clipPath> element. Then, inside the <clipPath> element, you can use a <use> element to reference the rectangle.

    (Yes, it's round-about and more complicated that you would think it should be, but that's how the SVG specs defined it.)

    Working from your code:

    var svg = d3.select("body")
        .append("svg")
    
    var clip = svg.append("defs").append("clipPath")
       .attr("id", "clipBox");
    
    svg.append('rect') // outline for reference
        .attr({x: margin.left, y: margin.top,
               width: width,
               height: height,
               id: "xSliceBox",
               stroke: 'black',
               'stroke-width': 0.5,
               fill:'white'});
    
    clip.append("use").attr("xlink:href", "#xSliceBox");
    
    svg.append("path")
        .attr("class", "line")
        .attr("d", slice(xy))
        .attr("clip-path", "url(#clipBox)") //CORRECTION
        .style("fill", "none")
        .style("stroke", "red")
        .style("stroke-width", 2);
    

    You could also do this the other way around, defining the rectangle within the clipPath element and then using a <use> element to actually draw it to the screen. Either way, you want to only define the rectangle once, so that if you decide to change it you only have to do it in one place and the other will update to match.

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