Как запустить svg анимацию с помощью Javascript? (Нет Jquery)



У меня есть путь линии svg, анимированный с этим образцом, который я нашел:






            svg{
position:absolute;
width:100%;
height:100%;
left:0%;
top:0%;
display:block;
background:transparent;
}

.path {
stroke:black;
stroke-dasharray: 290;
stroke-dashoffset: 130;
animation: dash 6s 0s forwards infinite;
stroke-width:2px;
stroke-linecap:round;
stroke-linejoin:round;
}

@keyframes dash {
from {
stroke-dashoffset: 290;
}
to {
stroke-dashoffset: 0;
}
}

           <svg viewbox="0 0 25 100" xmlns="http://www.w3.org/2000/svg">
<path class="path" d="M0 50 L 12 50, 12 0, 25 0" fill="transparent"></path>
</svg>





Это работает нормально, но его срабатывает, когда страница загружается, есть ли способ (скажем, с помощью кнопки), чтобы вызвать эту анимацию с помощью Javascript?



Я могу справиться с JS, но я нуб с CSS и svg анимациями.



Кто-нибудь может дать мне пример того, как я могу сделать это с моим фактическим css?



Спасибо.

831   4  

4 ответов:

Вы также можете использовать синтаксис анимации SMIL вместо анимации CSS. Это, по общему признанию, имеет обратную сторону-не работает в браузерах Microsoft (как IE, так и Edge).

var animation = document.getElementById("dash")
function showSVG(){
     animation.beginElement();
}
                svg{
                    position:relative;
                    width:100%;
                    height:150px;
                    left:0%;
                    top:0%;
                    display:block;
                    background:transparent;
                }
                
                .path {
                    stroke:black;
                    stroke-dasharray: 290;
                    stroke-dashoffset: 290;
                    stroke-width:2px;
                    stroke-linecap:round;
                    stroke-linejoin:round;
                }
<button id ="button" onclick="showSVG()">Click</button>
               <svg id="svg" viewbox="0 0 25 100" xmlns="http://www.w3.org/2000/svg">
                    <path class="path" d="M0 50 L 12 50, 12 0, 25 0" fill="transparent">
                        <animate id="dash" attributeName="stroke-dashoffset"
                            from="290" to="0"
                            begin="indefinite" dur="6s" fill="freeze" />
                   </path>
                </svg>
  

Эта анимация запускается один раз при каждом щелчке мыши. Если вы хотите, чтобы он повторялся через фиксированные интервалы, как предписывает CSS animation-repeat: infinite, Используйте

<animate id="dash" attributeName="stroke-dashoffset"
    from="290" to="0"
    begin="indefinite" dur="6s" repeatCount="indefinite" />
svg {
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0%;
    top: 0%;
    display: block;
    background: transparent;
}

.path {
    stroke: black;
    stroke-dasharray: 290;
    stroke-dashoffset: 130;
    stroke-width: 2px;
    stroke-linecap: round;
    stroke-linejoin: round;
    stroke-dashoffset: 290;
}

.animated {
    animation: dash 6s 0s forwards infinite;
    stroke-dashoffset: 0;
}

@keyframes dash {
    from {
        stroke-dashoffset: 290;
    }
    to {
        stroke-dashoffset: 0;
    }
}

Затем вы можете добавить класс .анимированный к вашему пути с js, когда вам это нужно.

Вы должны включить вашу анимацию в класс css:

    .dash-animate {
        animation: dash 6s 0s forwards infinite;
    }

    @keyframes dash {
      from {
        stroke-dashoffset: 290;
      }
      to {
        stroke-dashoffset: 0;
      }
    }

А затем просто примените этот класс, когда / где вы хотите, используя js:

var button = getElementById('some-button');

button.addEventListner('click', function() {
  var elements = document.querySelectorAll('.path');
  Array.prototype.forEach.call(elements, function(el) {
    el.classList.add('dash-animate');
  });
});

var svgPattern = document.getElementById("svg")
svgPattern.style.display = "none";
function showSVG(){
svgPattern.style.display = "block";
}
                svg{
                    position:absolute;
                    width:100%;
                    height:100%;
                    left:0%;
                    top:0%;
                    display:block;
                    background:transparent;
                }
                
                .path {
                    stroke:black;
                    stroke-dasharray: 290;
                    stroke-dashoffset: 130;
                    animation: dash 6s 0s forwards infinite;
                    stroke-width:2px;
                    stroke-linecap:round;
                    stroke-linejoin:round;
                }
                
                @keyframes dash {
                  from {
                    stroke-dashoffset: 290;
                  }
                  to {
                    stroke-dashoffset: 0;
                  }
                }
<button id ="button" onclick="showSVG()">Click</button>
               <svg id="svg" viewbox="0 0 25 100" xmlns="http://www.w3.org/2000/svg">
                    <path class="path" d="M0 50 L 12 50, 12 0, 25 0" fill="transparent"></path>
                </svg>
  

Comments

    Ничего не найдено.