Change SVG animation

2

I have an SVG animation which 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;

link

    
asked by anonymous 14.04.2015 / 12:12

1 answer

1

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

In any case, to change the speed of the animation, you need to change the attribute value dur in the animateTransform element.

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


Solution 1

Directly in the input, we can add a change event that will execute code whenever it changes.

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 duration of the animation, we will attach a click event to the 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>
    
14.04.2015 / 12:20