svg:如何绘制将在矩形区域之外裁剪的图形元素

Pix*_*ord 1 javascript svg d3.js

我正在尝试使用 d3.js 和 svg 渲染甘特图。该图表有两部分,一部分(迷你图表)显示完整的甘特图。其他(主图表)仅显示部分图表。

我在迷你图表中有一个视图窗口,我可以将其拖动到迷你图表上。现在主图表应该只渲染视图窗口内的部分(主图表作为迷你图表的缩放版本)。

现在我需要在主图表中呈现由“矩形”边框的数据。如何裁剪主图表区域之外的元素?

添加另一个 svg 作为主 svg 的内部可能是一个解决方案。还有其他方法吗?

谢谢。

Gil*_*sha 5

您可以使用ClipPath

示例代码

svg.append("clipPath") // define a clip path
  .attr("id", "rect-clip") // give the clipPath an ID
  .append("rect") //Append the shape for clipping
  .attr("x", 20)
  .attr("y", 20)
  .attr("width", 420)
  .attr("height", 260)
  .attr("fill", "#ccffff");

var chartElem1 = svg.append("circle")
  .attr("cx", 50)
  .attr("cy", 80)
  .attr("r", 40)
  .attr("fill", "#ffccff")
  .attr("fill-opacity", 0.6)
  .attr("clip-path", "url(#rect-clip)"); //Set clip-path using id
Run Code Online (Sandbox Code Playgroud)

svg.append("clipPath") // define a clip path
  .attr("id", "rect-clip") // give the clipPath an ID
  .append("rect") //Append the shape for clipping
  .attr("x", 20)
  .attr("y", 20)
  .attr("width", 420)
  .attr("height", 260)
  .attr("fill", "#ccffff");

var chartElem1 = svg.append("circle")
  .attr("cx", 50)
  .attr("cy", 80)
  .attr("r", 40)
  .attr("fill", "#ffccff")
  .attr("fill-opacity", 0.6)
  .attr("clip-path", "url(#rect-clip)"); //Set clip-path using id
Run Code Online (Sandbox Code Playgroud)
var dataset = {
  apples: [53245, 28479, 19697, 24037, 40245],
};

var width = 460,
  height = 300;

var svg = d3.select("body").append("svg")
  .attr("width", width)
  .attr("height", height)
  .style("background-color", "grey");

svg.append("clipPath") // define a clip path
  .attr("id", "rect-clip") // give the clipPath an ID
  .append("rect") //Append the shape for clipping
  .attr("x", 20)
  .attr("y", 20)
  .attr("width", 420)
  .attr("height", 260)
  .attr("fill", "#ccffff");

var chartContainer = svg.append("rect")
  .attr("x", 20)
  .attr("y", 20)
  .attr("width", 420)
  .attr("height", 260)
  .attr("fill", "#ccffff");

var chartElem1 = svg.append("circle")
  .attr("cx", 50)
  .attr("cy", 80)
  .attr("r", 40)
  .attr("fill", "#ffccff")
  .attr("fill-opacity", 0.6)
  .attr("clip-path", "url(#rect-clip)");

var chartElem2 = svg.append("rect")
  .attr("x", 10)
  .attr("y", 200)
  .attr("width", 100)
  .attr("height", 20)
  .attr("fill", "#ffccff")
  .attr("clip-path", "url(#rect-clip)");
Run Code Online (Sandbox Code Playgroud)
body {
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  margin: auto;
  position: relative;
  width: 960px;
}
Run Code Online (Sandbox Code Playgroud)