Change SVG animation

Asked

Viewed 148 times

2

I have an SVG animation that is a rotation. I want to change its speed through an input number (dur=variable).

<svg width=400px heigth=400px>
<rect ry=0 rx=0 x=100 y=100 width=50 height=50 fill="blue" id=rect>
    <animateTransform 
        attributeType="xml"
        attributeName="transform"
        type="rotate"
        from="0 125 125"
        to="360 125 125"
        dur="2"
        repeatCount="indefinite" 
    />
</rect>

javascript:

//obter valor da input
var x = document.getElementById("input_number").value;

http://jsfiddle.net/cr493jcw/

1 answer

1


Two solutions, depending on whether you want to work directly on the text box or make use of a button to trigger the update.

Anyway, to change the animation speed, you need to change the attribute value dur in the element animateTransform.

For this purpose, the simplest is to assign a id to this element to quickly identify it in the DOM as examples below.


Solution 1

Directly in input, we can add an event change which will execute code whenever it is changed.

Example also available on Jsfiddle.

var input = document.getElementById("input_number");

input.addEventListener("change", function handler(e) {
  document.getElementById("animacao").setAttribute('dur', input.value);
});
<svg width="400px" heigth="400px">
  <rect ry="0" rx="0" x="100" y="100" width="50" height="50" fill="blue" id="rect">
    <animateTransform id="animacao" attributeType="xml" attributeName="transform" type="rotate" from="0 125 125" to="360 125 125" dur="2" repeatCount="indefinite" />
  </rect>
</svg>
<input type="number" id="input_number" name="input_number" />


Solution 2

Using a button to update the chosen value for the new animation duration, we will attach an click button and execute a code snippet whenever it receives a click.

Example also available on Jsfiddle.

// Adicionar evento de clique ao botão
document.getElementById("alterar").addEventListener("click", handler);

// função chamada quando clicamos no botão
function handler(e) {

  // apanhar nova duração
  var novaDuracao = document.getElementById("input_number").value;

  // definir nova duração
  document.getElementById("animacao").setAttribute('dur', novaDuracao);
}
<svg width="400px" heigth="400px">
  <rect ry="0" rx="0" x="100" y="100" width="50" height="50" fill="blue" id="rect">
    <animateTransform id="animacao" attributeType="xml" attributeName="transform" type="rotate" from="0 125 125" to="360 125 125" dur="2" repeatCount="indefinite" />
  </rect>
</svg>
<input type="number" id="input_number" name="input_number" />
<button id="alterar">alterar</button>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.