Is it possible to set SVG object attributes as a number and not as a string?

I assign artificial attributes to an SVG-G element (an SVG group object). I move the group with its contents using SVG transforms, and I save the x / y coordinates of the group and its width / height in these attributes.

I am using the Javascript D3 library and the call:

embeddedElemContainer = nodeBoxContainer.append('svg:g') .attr('x', x) .attr('y', y) .attr('width', width) .attr('height', height) 

leads to the following object:

 <g transform="translate(13.585786437626904,31.585786437626904)" x="13.585786437626904" y="31.585786437626904" width="43.00000000000001" height="0"></g> 

This is normal, the only thing that bothers me is the fact that the attribute values ​​are stored as a string. If I want to use them for some calculations, I am forced to quit.

 parseInt(@embeddedElemContainer.attr('x')) 

Is there a way to store these values ​​directly as integer / double?

+7
source share
2 answers

The normal approach in D3 is to have lists of data associated with nodes. See Data Section in Selection API . D3 puts this in the __data__ property of the __data__ nodes that it creates / modifies. Internally, D3 pulls out this property and passes it as a parameter to various functions, but you can directly access it directly.

You can also associate an arbitrary data structure with a single node using the Datum method .

Without the rest of the context, this is hard to say, but below is a modified version of what I think you are trying to do:

 var vis = d3.select("body").append("svg").attr("width", 400).attr("height", 300); var groupData = {x: 100, y:100, height: 50, width: 50, theanswer : 42, thecolor: "blue", somedouble: 45.1651654 }; var embeddedElemContainer = vis.append('svg:g') .datum( groupData ) .attr( 'id', 'mygroup' ) .attr( 'x', function(d) { return dx; } ) .attr( 'y', function(d) { return dy; } ) .attr( 'height', function(d) { return d.height; } ) .attr( 'width', function(d) { return d.width; } ) // the regular DOM way: console.log(document.getElementById('mygroup').__data__) // the D3 way: console.log( d3.select('#mygroup').datum() ); 

Both console.log outputs are output:

 height: 50 somedouble: 45.1651654 theanswer: 42 thecolor: "blue" width: 50 x: 100 y: 100 
+5
source

You can override the d3 attr function to sniff out the numbers and make parseInt for you. This can lead to compatibility issues later, so it might be better to create a new attrInt function, for example:

 d3.selection.prototype.attrInt = function(name, value) { if(arguments.length == 1) { return parseInt(this.attr(name)); } else { return this.attr(name, value); } }; 

Disclaimer: I have no experience with d3, so I'm not sure if this is the right prototype to join; I just took it from looking at the source. :)

0
source

All Articles