SVG Setting Text Content Dynamically

Continuing on a theme of animating SVG, I’ve added a label in the center of the animation which contains the current angle of the ever-rotating marker (in fact in a centered horizontally and vertically SVG text node).

(Click image below to try it.)

image

At the bottom of the file from the previous post, I’ve added the following:

    <text id="currentValueAsText" x="300" y="300" 
        style="text-anchor: middle;alignment-baseline:middle" 
        fill="#FFFFFF" font-family="'Arial'" font-size="96" opacity=".6">0</text>

It’s a new text node. It’s set to centered both horizontally and vertically (using the text-anchor and alignment-baseline style properties respectively) at 300,300.

Setting the content is simple as well:

(function () {
    window.onload = loaded;
    function loaded() {
        var colorTemp = document.getElementById("color-temp");
        var reading = document.getElementById('current-reading');
        var currentVal = document.getElementById("currentValueAsText");
        var currentAngle = 0;
        var fill;

        var direction = 1;
        setInterval(function () {
            currentAngle += direction;
            if (currentAngle >= 120 || currentAngle <= -120) {
                direction *= -1;
            } else if (currentAngle === 0) {
                fill = direction === 1 ? "#BE1E2D" : "#10A2DC";
                colorTemp.setAttribute("fill", fill);
            }
            // adjust the opacity
            colorTemp.setAttribute("opacity", Math.abs(currentAngle) / 120.0);
            reading.setAttribute("transform", "rotate(" + currentAngle + ")");
            currentValueAsText.textContent = currentAngle.toString();

        }, 25);
    }
})();

Use the textContent property of the SVG text node to set the text.

Done. Smile