javascript - 使用纯 Javascript 制作 SVG 动画

标签 javascript animation svg

我正在尝试学习如何使用纯原生 Javascript 为 SVG 制作动画。我想让圆圈增大和缩小,同时在每个圆圈顶部显示一个标签,并显示一个代表其当前大小的值。

到目前为止,我有以下 SVG:

  <svg width="500" height="300" xmlns="http://www.w3.org/2000/svg">
        <path fill="none" d="M-1-1h502v302H-1z"/>
        <g>
          <path stroke-linecap="null" stroke-linejoin="null" stroke-opacity="null" stroke-width="4.5" stroke="#000" fill="none" d="M39.5 31.5v239M463.5 269.5l-422-1"/>
          <ellipse stroke="#bf0000" ry="65.5" rx="67" cy="165" cx="158.5" stroke-width="4.5" fill="none"/>
          <ellipse stroke="#007f00" ry="65.5" rx="67" cy="165" cx="361.5" stroke-width="4.5" fill="none"/>
        </g>
      </svg>

以下 JS 代码:

console.log("DOM Ready!");

var redCircle = document.getElementsByClassName('red');

var current = 0;
var destination = 700;
var friction = 0.04;


function loop() {
  console.log(redCircle.style.width);
  current += (destination - current) * friction;
  redCircle.style.width = (current * 0.5 + 'px');
  if (current >= destination - 0.1) {
    clearInterval(animation);
  }
}
var animation = setInterval(loop, 20);

我的问题是开发工具 console.log 说:

Uncaught TypeError: Cannot set property 'width' of undefined at loop 

最佳答案

document.getElementsByClassName 返回一个数组而不是一个对象。另外,您的 html 中没有名为“red”的类,因此脚本中返回的数组是 = []。一个空数组。当您调用 .style 时,您基本上是在调用 [].style。由于样式不作为数组上的属性存在(它是未定义的)。然后,您尝试获取不存在的属性([].style)的属性(.width),这是不可能的,因此 Javascript 除了抛出错误之外什么也做不了。

console.log("DOM Ready!");

var redCircle = document.getElementsByClassName('red');

var current = 0;
var destination = 700;
var friction = 0.04;

function loop() {
  // console.log(redCircle[0].style);
  current += (destination - current) * friction;
  redCircle[0].style.width = (current * 0.5 + 'px');
  if (current >= destination - 0.1) {
    clearInterval(animation);
  }
}
var animation = setInterval(loop, 20);
  <svg width="500" height="300" xmlns="http://www.w3.org/2000/svg" class="red">
        <path fill="none" d="M-1-1h502v302H-1z"/>
        <g>
          <path stroke-linecap="null" stroke-linejoin="null" stroke-opacity="null" stroke-width="4.5" stroke="#000" fill="none" d="M39.5 31.5v239M463.5 269.5l-422-1"/>
          <ellipse stroke="#bf0000" ry="65.5" rx="67" cy="165" cx="158.5" stroke-width="4.5" fill="none"/>
          <ellipse stroke="#007f00" ry="65.5" rx="67" cy="165" cx="361.5" stroke-width="4.5" fill="none"/>
        </g>
      </svg>

关于javascript - 使用纯 Javascript 制作 SVG 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45527754/

相关文章:

javascript - 正则表达式测试并将结果存储在 javascript 中

javascript - React js 中的自调用函数? (与常规 javascript 一样)

ios - 递增数字动画

android - 更流畅的动画 ImageSwitcher

javascript - SVG 缩放和平移 JavaScript

javascript - d3 缩放 : prevent page zoom when using a touchscreen

javascript - 我可以从 android 浏览器 JavaScript 中获取哪些信息?

android - 为什么我的 Android 动画不调用我的 onAnimationEnd?

javascript - D3 SVG 无法响应调整大小

javascript - 我可以在不改变 html 标签的情况下编辑 body 的 innerText 吗?