Reputation: 641
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).
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?
Adding another svg as the inside the main svg could be a solution. Is there any other way to do it?
Thanks.
Upvotes: 1
Views: 1093
Reputation: 14589
You can use clipPath.
Sample Code
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>
Upvotes: 5