// animate : <animate attributeName="viewBox" ...>
// rect : {SVGRect} result of polygonElement.getBBox();
function animateViewBox(animate, rect) {
animate.setAttribute('from', animate.getAttribute('to'));
animate.setAttribute('to', `${rect.x} ${rect.y} ${rect.width} ${rect.height}`);
animate.beginElement(); // (re)start the animation
}
一旦有了这个,我们只需要设置一个函数来遍历 svg 中的所有 元素。
function animateViewBox(animate, rect) {
animate.setAttribute('from', animate.getAttribute('to'));
animate.setAttribute('to', `${rect.x} ${rect.y} ${rect.width} ${rect.height}`);
animate.beginElement(); // (re)start the animation
}
// container
const svg = document.getElementById('svg1413');
// all the <polygons> coordinates (would be better as JSON...)
const polygons = svg.querySelectorAll('polygon');
// <animate> element
const animator = svg.querySelector('.viewBoxAnimator');
// our iterator, we could call it on click
let i = 0;
function iterate() {
if (i < polygons.length) {
animateViewBox(animator, polygons[i++].getBBox());
return true;
}
}
// but we'll automate it
(async() => {
while (iterate()) {
await wait(1500);
}
})();
function wait(time) {
return new Promise(res => setTimeout(res, time));
}
svg {
width: 100%;
height: 100%;
max-width: 100vw;
max-height: 100vh;
transition: all .6s;
}
html {
background: black;
}
// Reference to svg
const canvas = SVG('#svg1413')
// List of all polygons
const polygons = canvas.find('#SvgjsG1413 polygon')
// List of all bboxes
const boxes = polygons.bbox()
const nextImage = function (index) {
// Animate viewbox over 1s to new box
canvas.animate(1000).viewbox(boxes[index])
// Next image in 2s
setTimeout(() => nextImage(++index), 2000)
}
nextImage(0)