如何剪辑 SVG 图?

How to clip an SVG plot?

我的 SVG 元素设置如下:

svg.attr("viewBox", "0 0 " + chartView.displayWidth + " " + chartView.displayHeight);

我在里面画了一些图。有没有办法创建一个 "see through window" 在里面我可以看到我的地块?

我尝试使用:

svg.append("clipPath").append("rect")
                    .attr("x", 10)
                     .attr("y", 10)
                    .attr("width", 50)
                   .attr("height", 100);

但是没用

如评论中所述,您将使用 ClipPath。 您已经尝试使用 append 创建一个。据我所知,这是 D3.jsjQuery 语法。但是你标记了 svg.js。 在 svg.js 你会这样做:

svg.viewbox(0, 0, chartView.displayWidth, chartView.displayHeight);

var plot = svg.path('your plots path data').stroke('#000')

var clipper = svg.rect(50, 100).move(10, 10)

// to clip the whole svg use svg instead of plot
plot.clipWith(clipper)

如果您使用 D3.js,您就快到了。 您已经创建了剪辑路径。你现在必须给它一个 id,并在你的情节中引用这个 id。

var clip = svg.append("clipPath").attr("id", "clipper");
clip.append("rect").attr("x", 10)
                   .attr("y", 10)
                   .attr("width", 50)
                   .attr("height", 100);

yourplot.attr("clip-path", "url(#clipper)")

如果你想用你的矩形剪辑整个 svg,请使用 svg.attr(...) 而不是 yourplot.attr(...)

确保阅读 svg 规范或一些关于 clipPaths 的教程