Reputation: 15
I'm having trouble making a SVG text element with javascript. The problem is that it is not scaling like it should when window resizes.
Look at this fiddle: https://jsfiddle.net/cduL72mf/2/
Why is the javscript-generated "SVGtext 2" not behaving like "SVGtext 1", what I can see the output is exactly the same? What am I missing?
var xmlns = 'http://www.w3.org/2000/svg';
var svgelement = document.createElementNS(xmlns, 'svg');
svgelement.id='svg2';
svgelement.setAttribute('viewbox', '0 0 300 200');
document.body.appendChild(svgelement);
var svgtext = document.createElementNS(xmlns, 'text');
svgtext.id='text2';
svgtext.setAttribute('x', '56');
svgtext.setAttribute('y', '74');
svgtext.setAttribute('font-size', '33');
var textnode = document.createTextNode('SVGText 2');
svgtext.appendChild(textnode);
svgelement.appendChild(svgtext);
svg {
width: 100%;
height: 300px;
}
<svg id="svg1" viewbox="0 0 300 200">
<text id="text1" x="56" y="74" font-size="33">SVGText 1</text>
</svg>
Upvotes: 1
Views: 435
Reputation: 101936
viewbox
should be viewBox
. It is case-sensitive.
The lower-case version in the other SVG ("svg1") is accepted because the HTML parser is more forgiving. It corrects that attribute name for you.
var xmlns = 'http://www.w3.org/2000/svg';
var svgelement = document.createElementNS(xmlns, 'svg');
svgelement.id='svg2';
svgelement.setAttribute('viewBox', '0 0 300 200');
document.body.appendChild(svgelement);
var svgtext = document.createElementNS(xmlns, 'text');
svgtext.id='text2';
svgtext.setAttribute('x', '56');
svgtext.setAttribute('y', '74');
svgtext.setAttribute('font-size', '33');
var textnode = document.createTextNode('SVGText 2');
svgtext.appendChild(textnode);
svgelement.appendChild(svgtext);
svg {
width: 100%;
height: 300px;
}
<svg id="svg1" viewbox="0 0 300 200">
<text id="text1" x="56" y="74" font-size="33">SVGText 1</text>
</svg>
Upvotes: 1