2

My SVG element is setup as this:

svg.attr("viewBox", "0 0 " + chartView.displayWidth + " " + chartView.displayHeight);

inside I'm drawing some plots. Is there a way to create a "see through window" inside which I can see my plots?

I tried using:

svg.append("clipPath").append("rect")
                    .attr("x", 10)
                     .attr("y", 10)
                    .attr("width", 50)
                   .attr("height", 100);

but it doesn't work

Gianluca Ghettini
  • 11,129
  • 19
  • 93
  • 159

1 Answers1

1

As already mentioned in the comments you would use a ClipPath. You already tried to create one using append. As far as I know, this is D3.js or jQuery syntax. But you tagged svg.js. In svg.js you would do it like this:

svg.viewbox(0, 0, chartView.displayWidth, chartView.displayHeight);

var plot = svg.path('your plots path data').stroke('#000')

var clipper = svg.rect(50, 100).move(10, 10)

// to clip the whole svg use svg instead of plot
plot.clipWith(clipper)

If you use D3.js you are almost there. You already created the clippath. You now have to give it an id, and reference this id in your plot.

var clip = svg.append("clipPath").attr("id", "clipper");
clip.append("rect").attr("x", 10)
                   .attr("y", 10)
                   .attr("width", 50)
                   .attr("height", 100);

yourplot.attr("clip-path", "url(#clipper)")

If you want to clip the whole svg with your rect, use svg.attr(...) instead of yourplot.attr(...)

Make sure to read the svg specification or some tutorial about clipPaths

Fuzzyma
  • 7,619
  • 6
  • 28
  • 60
  • In refer to my question, "yourPlot" should be "svg". Don't forget semicolons in your JavaScript answers. Seems silly, but in Javascript a missing semicolon is a PITA to debug. Ok it works.. Answer accepted – Gianluca Ghettini May 09 '16 at 10:12
  • not necessarily. If you want to window each indivudial plot, you have to do it as I wrote. You never should edit an answer without giving a note what you changed and why. The svg.js version now doenst fit the d3 version. Will change it accordingly – Fuzzyma May 09 '16 at 10:17
  • The SVG has a viewBox on it so you're unlikely to get the result you expect if you put a clipPath on the `` element itself. – Robert Longson May 09 '16 at 10:20