svg:如何绘制将在矩形区域外裁剪的图形元素 [英] svg: how to draw graph elements that will be crop outside a rectangular area

查看:128
本文介绍了svg:如何绘制将在矩形区域外裁剪的图形元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to render gantt chart using d3.js and svg. The chart has two part, one (the mini chart) display the complete gantt chart. Other (the main chart) display only partial of the chart.

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

I have a view window in in the mini chart which I can drag over the mini chart. Now the main chart is supposed to render only the portion inside the view widow (main chart works as a zoomed version of the mini chart).

现在我需要在主图表中呈现由rect定界的数据。
如何裁剪主图表区域以外的元素?

Now I need to render the data in the main chart which is bordered by a "rect". How can I crop the elements that goes outside that main chart area?

在主svg中添加另一个svg可能是一个解决方案。有其他方法吗?

Adding another svg as the inside the main svg could be a solution. Is there any other way to do it?

谢谢。

推荐答案

您可以使用 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>

这篇关于svg:如何绘制将在矩形区域外裁剪的图形元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆