I am trying to have a SVG which pulls some text from a .txt file and displays it. Here is my code so far.
<svg width="10cm" height="3cm" viewBox="0 0 1000 300" version="1.1"
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<text x="100" y="200" font-size="45" fill="red" >
<tref xlink:href="sensors.txt"/>
</text>
</svg>
I don't understand why its not working.
To fix your non-functional <tref>
elements, you can add a script to the end of the SVG that loads the desired text files via Ajax:
<svg width="10cm" height="3cm" viewBox="0 0 1000 300" version="1.1"
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<text x="100" y="200" font-size="45" fill="red" >
<tref xlink:href="sensors.txt"/>
</text>
<script type="text/javascript">
var trefs = document.getElementsByTagName("tref");
for (var i=0; trefs[i]; i++) {
var xhr = new XMLHttpRequest();
xhr.open("GET",trefs[i].getAttributeNS("http://www.w3.org/1999/xlink","href"),false);
xhr.send("");
trefs[i].parentNode.replaceChild(document.createTextNode(xhr.responseText),trefs[i]);
}
</script>
</svg>
Of course, this only works for referencing text files, as you do. This could be stylistically refined and, if needed, also be made working for references of text via IDs, like xlink:href="#textId'
, even for referenced IDs from external files, like xlink:href="other.svg#textId"
.
I'm not sure whether it can sensibly be sniffed whether the browser already supports all needed aspects of <tref>
to only run the script if necessary.