I’m beginning to just learn some SVG (and javascript, I suppose), and I’m having a hard time understanding why this is not flowing smoothly. The 0 moves a small amount (presumably “1” horizontally on the x axis), but than begins to leap in great bounds. Is this because the browser I am using (Chrome) is refreshing/redrawing at a much longer pace? Any input would be greatly appreciated.
<svg width="100%" height="100%"
xmlns="http://www.w3.org/2000/svg" version="1.1"
xmlns:xlink="http://www.w3.org/1999/xlink"
onload="startup(evt)">
<script>
function startup(evt){
svgDoc=evt.target.ownerDocument;
setInterval(function(){
e=svgDoc.getElementById("zero");
var x = e.getAttribute("x");
e.setAttribute("x",x+1);
},1000);
}
</script>
<defs>
<text id="zero">0</text>
</defs>
<use x="40" y="20" xlink:href="#zero"/>
</svg>
You have to make sure you’re working with numbers and not strings:
JavaScript prefers string “addition” to numeric, so when “x” is a string,
x+1means “add the character ‘1’ to the end of the string x”. By forcing the return value from.getAttribute()to numeric via the unary “+” operator, you avoid that problem.(There are various ways to force a string to be converted to a number. Pick your favorite 🙂