【问题标题】:Svg animations replaying in the same spotSvg 动画在同一个地方重播
【发布时间】:2021-07-14 02:31:03
【问题描述】:

我正在开发一款带有 HTML、CSS 和 JS 的塔防游戏。我希望能够使用 svg 动画创建遵循路径的 svg 圆圈。为了做到这一点,我写了这段代码:

<div id="trackPart">
  <progress id="healthBar" max="200" value="200" onclick="this.value = randInt(0, this.max)" ></progress>
  <svg viewbox="0 0 1000 3000" id="track" xmlns="http://www.w3.org/2000/svg">
    <path id="path" fill="none" stroke="red" stroke-width="15" d="M 0, 50 h 900 v 100 h -800 v 100 h 800 v 300 h -900" style="cursor: pointer"/>
  </svg>
</div>
var path = document.getElementById("path")
var svgurl = "http://www.w3.org/2000/svg"
var svg = document.getElementById("track")

listOfColors = ["green", "blue", "purple", "lime", "yellow"]

function attackerSVG(color) {
  let element = document.createElementNS(svgurl, "circle")
  element.setAttribute("cx", 0)
  element.setAttribute("cy", 0)
  element.setAttribute("r", 15)
  element.setAttribute("fill", color)

  let animation = document.createElementNS(svgurl, "animateMotion")
  animation.setAttribute("dur", "30s")
  animation.setAttribute("repeatCount", "indefinite")
  animation.setAttribute("rotate", "auto")
  animation.setAttribute("path", String(path.getAttribute("d")))
  animation.setAttribute("onrepeat", "console.log(\"repeat\")")
  animation.setAttribute("restart", "always")
  animation.beginElement()

  element.appendChild(animation)
  svg.appendChild(element)
  return element
}

attackerSVG("black")

我第一次运行 AttackSvg 函数时,一切正常。在路径的开始处创建一个圆圈并跟随它。但是,一旦我创建了另一个,它就会在其他 svg 圆圈所在的位置开始其动画序列。如果你想明白我的意思,你可以去这里 https://replit.com/@hello1964/Tower-defense-game#script.js

每当您看到圆圈改变颜色时,就表示正在创建一个新圆圈。当您在控制台中查看时,每次一个圆圈完成一个循环时,它都会打印“重复”。由于它们都在同一个位置,它会打印多次。非常感谢您的帮助,谢谢。

【问题讨论】:

    标签: javascript animation svg path


    【解决方案1】:

    SVG 保持自己的时序。向 SVG 添加一个元素,将在当前时钟启动它。做自己想做的事,其实需要延迟启动

    // outside globally somwhere
    let count = 0;
    
    // inside function attackerSVG
    animation.setAttribute('begin', `${++count}s`)
    

    【讨论】:

      猜你喜欢
      • 2019-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-26
      • 2019-10-07
      相关资源
      最近更新 更多