D3.js-how To Clip Area Outside Rectangle While Zooming In A Grouped Bar Chart
Solution 1:
Here's an updated jsfiddle
It comes down to a few modifications. First, you need to know about SVG clip-path
which is a way to define an svg shape that masks or crops another shape (your chart, in this case). As demonstrated in the linked documentation, a clip-path
requires a <defs>
element with a <clipPath>
inside it. In your case, that <clipPath>
needs to contain a <rect>
whose bounds are set to cover the visible area.
To create that <defs>
, I added:
var mask = svg.append("defs")
.append("clipPath")
.attr("id", "mask")
.style("pointer-events", "none")
.append("rect")
.attr({
x: 0,
y: 0,
width: width,
height: height + margin.bottom,
})
Ultimately, to use the above mask to crop the chart, it required calling
.attr("clip-path", "url(#mask)")
on the thing that is being masked.
The way you had things set up, there was no single SVG <g>
that contained both of the things that needed to be mask (i.e. the chart and the x-axis). So I added that <g>
, and reshuffled things so that the axis and chart (allStates
) are added to it:
var masked = svg.append("g")
.attr("clip-path", "url(#mask)")
masked.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
var allStates = masked
.append("g")
.attr("class", "allStates");
And that's all.
Solution 2:
What about that?
function zoom() {
svg.select(".allStates").attr("transform", "translate(" + d3.event.translate[0] + ",0)scale(" + d3.event.scale + ",1)");
svg.select(".x.axis").attr("transform", "translate(" + d3.event.translate[0] + "," + (height) + ")").call(xAxis.scale(x0.rangeRoundBands([0, width * d3.event.scale], .5 * d3.event.scale)));
//svg.select(".y.axis").call(yAxis);
svg.select(".y.axis").attr("transform", "translate(" + (d3.event.translate[0]-d3.event.scale) + ", 0)")
}
I just added the last line to move the Y axis to the left when zooming.
Let me know if that's enough for you.
Post a Comment for "D3.js-how To Clip Area Outside Rectangle While Zooming In A Grouped Bar Chart"