首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >svg:如何绘制将在矩形区域外裁剪的图形元素

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

Stack Overflow用户
提问于 2016-01-12 16:27:55
回答 1查看 956关注 0票数 1

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

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

现在,我需要在主图表中呈现数据,该图表的边界是一个"rect“。如何裁剪位于该主图表区域之外的元素?

添加另一个svg作为主svg的内部可能是一种解决方案。还有没有别的办法呢?

谢谢。

EN

回答 1

Stack Overflow用户

发布于 2016-01-12 17:32:46

您可以使用clipPath

示例代码

代码语言:javascript
复制
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

代码语言:javascript
复制
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)");
代码语言:javascript
复制
body {
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  margin: auto;
  position: relative;
  width: 960px;
}
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34738746

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档