Как запустить анимацию SVG с Javascript? (Нет Jquery) - PullRequest
0 голосов
/ 02 мая 2018

У меня есть путь линии 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?

Спасибо.

Ответы [ 4 ]

0 голосов
/ 02 мая 2018

Вы можете также использовать синтаксис 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" />
0 голосов
/ 02 мая 2018

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>
  
0 голосов
/ 02 мая 2018
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;
    }
}

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

0 голосов
/ 02 мая 2018

Вы должны включить свою анимацию в класс 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');
  });
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...