Tengo este código svg que produce 3 rectángulos que cambian de color. Quiero congelarlos haciendo clic en cualquiera de estos 3 rectángulos, pero soy nuevo en svg y no tengo idea de cómo hacerlo. Lo intenté usando javascript, pero no funcionó. ¿Algunas ideas?
<svg width="500" height="500" onclick="freezing()"> <rect x="10" y="20" width="90" height="60"> <animate id="a1" attributeName="fill" from="red" to="blue" dur="3s" fill="freeze" /> </rect> <rect x="10" y="120" width="90" height="60"> <animate id="a2" attributeName="fill" from="blue" to="yellow" dur="3s" fill="freeze" /> </rect> <rect x="10" y="220" width="90" height="60"> <animate id="a3" attributeName="fill" from="yellow" to="green" dur="3s" fill="freeze" /> </rect> </svg>Puede usar el método SVGSVGElement#pauseAnimations para pausar las animaciones SMIL que se ejecutan dentro de este elemento. Para reanudarlo, puede llamar a unpauseAnimations() uno.
const svg = document.querySelector("svg"); svg.onclick = (evt) => { if (svg.animationsPaused()) { svg.unpauseAnimations(); } else { svg.pauseAnimations(); } }; <svg width="500" height="500" > <rect x="10" y="20" width="90" height="60"> <animate id="a1" attributeName="fill" from="red" to="blue" dur="3s" fill="freeze" /> </rect> <rect x="10" y="120" width="90" height="60"> <animate id="a2" attributeName="fill" from="blue" to="yellow" dur="3s" fill="freeze" /> </rect> <rect x="10" y="220" width="90" height="60"> <animate id="a3" attributeName="fill" from="yellow" to="green" dur="3s" fill="freeze" /> </rect> </svg>Es realmente difícil combinar animaciones SMIL en SVG con JavaScript. Aquí reemplacé los elementos animados con objetos de animación en JavaScript. Un objeto de animación tiene diferentes métodos como play(), pause() y cancel().
Al llamar a Element.getAnimations() puede obtener todas las animaciones de un elemento. Es una matriz, por lo que debe iterar sobre ella y pausar todas (en este caso, solo una) las animaciones.
let timingoptions = { duration: 3000, fill: 'forwards' }; document.querySelector('rect:nth-child(1)').animate([ {fill: 'red'}, {fill: 'blue'} ], timingoptions); document.querySelector('rect:nth-child(2)').animate([ {fill: 'blue'}, {fill: 'yellow'} ], timingoptions); document.querySelector('rect:nth-child(3)').animate([ {fill: 'yellow'}, {fill: 'green'} ], timingoptions); document.querySelector('svg').addEventListener('click', e => { e.target.getAnimations().forEach(animation => animation.pause()); }); <svg width="500" height="500"> <rect x="10" y="20" width="90" height="60"/> <rect x="10" y="120" width="90" height="60"/> <rect x="10" y="220" width="90" height="60"/> </svg>