Accessing dimensions of SVG component in Aurelia

2019-09-16 09:57发布

问题:

I'm porting over a d3 application into Aurelia and need to access the width and height of the chart's SVG parent in order to fit the chart properly to the current screen dimensions.

Before porting, it looked like this, filling up the whole container properly:

This is what it looks like in Aurelia:

It sets its dimensions by calling d3.select('#timeline-svg').style('width') and d3.select('#timeline-svg').style('height'). But now, in Aurelia, whenever I call those it returns dimensions of 300 x 150, no matter what the dimensions of the SVG actually are. I tried calling the same code on the SVG's div parent (which has identical dimensions) and that didn't help either.

So then I thought to try two-way data binding and changed my SVG tag to <svg id="timeline-svg" width.two-way="width"></svg> (and declared a corresponding width variable in my view-model), but I get the error: Error: Observation of a "svg" element's "width" property is not supported.

I've even tried using aurelia-pal, injecting it as DOM and calling:

attached() {console.log(this.DOM.getElementById("timeline-svg").style.width);} but all that gives me is an empty string.

There's a gist here (minus the d3 code, but all I want to figure out is how to access the dimensions of the SVG element in app.html from within app.js). What am I doing wrong? Thanks!

回答1:

I'm not sure if this is exactly what you're looking for, but you could use the ref custom attribute to get a reference the svg element itself.

<svg ref="svgElement"></svg>

Then use the getBBox() function. The result of that function will have a width property you can use.

this.svgElement.getBBox().width

Here's a simple gist example: https://gist.run/?id=0ed86f511533512a22d002675221d812