Reputation: 315
as I'd like to check wether d3js could do with my wishes, I Need to know how to create an svg-element, from a given string.
My Elements are stored in a database. They are Strings, that follow the svg rules, like the following:
<desc>
<Insert x='21' y='21'/>
<Pins>
<Pin Id='1' x='21' y='1' direction='up' />
<Pin Id='2' x='21' y='41' direction='down' />
</Pins>
<Properties>
<Property Id='20010' x='0' y='21' angle='0'></Property>
</Properties>
</desc>
<circle class='CDC300' cx='21' cy='21' r='20' fill='none'></circle>
<polyline class='CDC300' points='1 21 21 1 41 21' fill='none' />
<text id='20010' class='CDC400' text-anchor='end' x='-2' y='25' >#{BMK}</text>
Before creating a svg-element out of this string, I'd like to add a g-tag (Group) and I Need to add transform='translate( some value of database )'. Ok, the last Thing I hope I could do better with d3.
So how do I begin? I found tons of examples and tutorials but None of them stored the svg-elements in a databse, Only some coordinates or very simple data to place and style the svg.
Upvotes: 1
Views: 1627
Reputation: 102174
For modern browsers* you can use html()
for appending the whole string to your <g>
element.
Here is a basic demo. We first create the <g>
element, then translate it by the value you want, and finally we use the string from the database:
const string = `<desc>
<Insert x='21' y='21'></Insert>
<Pins>
<Pin Id='1' x='21' y='1' direction='up'/>
<Pin Id='2' x='21' y='41' direction='down'/>
</Pins>
<Properties>
<Property Id='20010' x='0' y='21' angle='0'></Property>
</Properties>
</desc>
<circle class='CDC300' cx='21' cy='21' r='20' fill='blue'></circle>
<polyline class='CDC300' points='1 21 21 1 41 21' fill='red' />
<text id='20010' class='CDC400' text-anchor='end' x='-2' y='25' >#{BMK}</text>`;
const svg = d3.select("svg");
const g = svg.append("g").attr("transform", "translate(100,50)");
g.html(string);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg></svg>
Also, for that to work, you have to properly close the elements, like:
<Insert x='21' y='21'></Insert>
* Because html
uses innerHTML
internally, that won't work on SVG elements in old browsers.
Upvotes: 1