Offline, Fullscreenable HTML5 Compass with SVG [Part 2 - Animating Things]

Where we last left off, we had constructed this famous-looking compass:

<svg viewBox="0, 0, 100, 100">  
  <g id="compass">
   <circle id="compassBody" cx="50" cy="50" r="48" style="fill: white; stroke: black;" />
  </g>
  <g id="needle">
    <polygon id="needleBody" points="50,98 60,50 50,2 40,50" style="fill: black;"/>
    <polygon id="needleTip" points="50,2 55,25 45,25" style="fill: red;" />
    <text x="50" y="20" font-family="Arial" font-size=".5em" text-anchor="middle">
     N
    </text>
    <circle id="needleCenter" cx="50" cy="50" r="3" style="fill: white;" />
  </g>
</svg>  

However, we're going to need a way to rotate the needle. One way to approach this is with changes to the transform attribute:

var needle = document.getElementById('needle');  
needle.setAttribute('transform','rotate(15)');  
N

Whoops! There's something wrong with that!

Actually, it's right and we're wrong. The needle is rotated 15 degrees- about the origin at (0,0). If we want to rotate it 15 degrees, we need to translate the center to our origin at (50,50), then rotate it, then translate it back where we want it again:

var needle = document.getElementById('needle');  
needle.setAttribute('transform',  
  'translate(50, 50) rotate(15) translate(-50, -50)'
);
N

Great! Now let's make it move:

  var needle = document.getElementById('needle3');
  var rotation = 0;
  setInterval(function() {
    rotation = 
      (rotation >= 355 ? 
        rotation-355 : 
        rotation+55);
    needle.setAttribute('transform',
    'translate(50, 50) rotate('+
    rotation+
    ') translate(-50, -50)');
  },50);
N
How to Cite Republished Information

Do not use this information as legal advice.
If you need advice, call or email a licensed attorney.
No attorney-client relationship is created by your use of this site, including any communication with the author in comments.