![](/img/trans.png)
[英]How to draw a line (path, svg) between two elements that aren't always rectangular
[英]svg: how to draw graph elements that will be crop outside a rectangular area
我正在尝试使用d3.js和svg渲染甘特图。 图表分为两部分,一个(迷你图表)显示完整的甘特图。 其他(主图表)仅显示部分图表。
我在迷你图表中有一个查看窗口,可以将其拖到迷你图表上。 现在,主图表应该只渲染视图寡妇内部的部分(主图表用作迷你图表的缩放版本)。
现在,我需要在以“矩形”为边界的主图表中呈现数据。 如何裁剪超出主要图表区域的元素?
在主svg的内部添加另一个svg可能是一种解决方案。 还有其他方法吗?
谢谢。
您可以使用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
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)");
body { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; margin: auto; position: relative; width: 960px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.