使用现有对象作为剪切路径的简单方法?

Bry*_*son 2 javascript svg d3.js

我有以下简单的示例,当直线延伸到矩形之外时,我想对其进行裁剪。我已经将矩形用作轮廓,将矩形作为剪切路径的简单方法是什么?我当前使用的方法id被忽略。这个相关问题有一个答案,但它需要单独创建剪辑区域。我想重复使用我的信息,而不要重复几乎相同的信息。

<!DOCTYPE html>
<meta charset="utf-8">

<body>
<script src = "http://d3js.org/d3.v3.min.js"> </script>
<script>

var margin = {top: 100, right: 20, bottom: 20, left: 20},
    width = 600 - margin.left - margin.right,
    height = 270 - margin.top - margin.bottom;

var xdata = d3.range(0, 20);
var ydata = [1, 4, 5, 9, 10, 14, 15, 15, 11, 10, 5, 5, 4, 8, 7, 5, 5, 5, 8, 10];


var xy = []; // start empty, add each element one at a time
for(var i = 0; i < xdata.length; i++ ) {
   xy.push({x: xdata[i], y: ydata[i]});
}

var xscl = d3.scale.linear()
    .domain(d3.extent(xy, function(d) {return d.x;})) //use just the x part
    .range([margin.left, width + margin.left])

var yscl = d3.scale.linear()
    .domain([1, 8]) // use just the y part
    .range([height + margin.top, margin.top])

var slice = d3.svg.line()
  .x(function(d) { return xscl(d.x);}) // apply the x scale to the x data
  .y(function(d) { return yscl(d.y);}) // apply the y scale to the y data

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

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

svg.append("path")
    .attr("class", "line")
    .attr("d", slice(xy))
    .attr("clip-path", "#xSliceBox")
    .style("fill", "none")
    .style("stroke", "red")
    .style("stroke-width", 2);

</script>
</body>
Run Code Online (Sandbox Code Playgroud)

Ame*_*aBR 5

您不能直接在clip-path属性中引用矩形,需要创建一个<clipPath>元素。然后,可以在<clipPath>元素内部使用<use>元素来引用矩形。

(是的,这是您应该认为的绕线操作,更复杂,但这就是SVG规范定义它的方式。)

从您的代码工作:

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);
Run Code Online (Sandbox Code Playgroud)

您也可以采用另一种方法,在clipPath元素内定义矩形,然后使用<use>元素将其实际绘制到屏幕上。无论哪种方式,您都只想定义一次矩形,这样,如果您决定更改矩形,则只需要在一个位置进行操作,而另一位置将进行更新以匹配。