javascript - 如何为未硬编码的 SVG 制作动画?

标签 javascript image dom svg svg-animate

我无法为使用 img 标签导入的 svg 制作动画。我无法对 svg 进行硬编码,因为我的项目是在使用 webpack 进行预处理期间生成的。遗憾的是,我似乎无法通过 svg 标记获取我的文件,因为我不知道任何“src”或“href”属性。

如何为未硬编码的 SVG 制作动画?

最佳答案

这实际上取决于动画的驱动方式。

<小时/>

生成动画 SVG 基本上有三种方法:

  • SMIL Animation - 不幸的是,并没有得到真正广泛的支持(但是你确实用[svg-animate]进行了标记,所以让我们将其作为第一种情况)。
  • CSS Animation - 随着SVG2的出现,我敢打赌这些会变得越来越普遍。
  • 基于脚本的动画。

当它们 <svg> 时,这些行为如何? documentElement 嵌入在 <img> 中标签?

<小时/>

<img> 中的 SMIL 动画.

在支持的浏览器中,这些将正常运行,就好像您的 SVG 未嵌入一样。
您将面临的唯一限制是

  • 您不会收到任何用户手势,因此 element.click和类似的事件将不起作用
  • 对于不支持 SMIL 动画的浏览器(IE...),您无法回退到基于脚本的动画。

这两个限制不会影响 <object> 中加载的 SVG , <embed><iframe> ,所以如果您需要的话,您可以使用它。

var svgStr = `
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" width="50" height="50">
    <rect id="rect" x="-30" y="0" width="30" height="50">
      <!-- this will work normally, even in an <img> -->
      <animate attributeType="XML" attributeName="x" from="-30" to="50"
        begin="0s" dur="10s" repeatCount="indefinite"/>
      <!-- this will not work in <img>, but will in <object>/<iframe>/<embed> -->
      <animate attributeType="XML" attributeName="fill" from="blue" to="red"
        begin="rect.click"
        dur="1s" repeatCount="1"/>
    </rect>
    <!-- js-based workaround won't work in <img> but will in <object>/<iframe>/<embed> -->
    <script src="https://cdn.rawgit.com/FakeSmile/FakeSmile/23c5ceae/smil.user.js"><\/script>
  </svg>`;

loadSVG(document.images[0]);
loadSVG(document.querySelector('object'));

function loadSVG(container) {
  var url = URL.createObjectURL(new Blob([svgStr], {type: 'image/svg+xml'}));
  container.src = container.data = url;
}
img{
  border: 1px solid green;
}
object{
  border: 1px solid blue;
}
<img src="">
<object></object>
<div>Try to click the black rectangle in both the <code>&lt;img></code> and <code>&lt;object></code> tags.

<img> 中的 CSS 动画.

就像 SMIL 动画一样,它们应该在支持浏览器中工作,具有相同的用户手势限制,以及相同的可能方法(使用其他容器):

var svgStr = `
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" width="50" height="50">
    <rect id="rect" x="0" y="0" width="30" height="50"/>
    <defs>
      <style>
        #rect {
          /* this will work normally, even in an img */
          animation: move 10s linear infinite;
        }
        #rect:hover {
          /* this will not work in img, but will in object/iframe/embed */
          animation: move 10s linear infinite, color 1s 1;
        }
        @keyframes move {
          from {
            transform: translate(-30px, 0px);
          }
          to {
            transform: translate(50px, 0px);
          }
        }
        @keyframes color {
          from {
            fill: blue;
          }
          to {
            fill: red;
          }
        }
      </style>
    </defs>
  </svg>`;

loadSVG(document.images[0]);
loadSVG(document.querySelector('object'));

function loadSVG(container) {
  var url = URL.createObjectURL(new Blob([svgStr], {type: 'image/svg+xml'}));
  container.src = container.data = url;
}
img{
  border: 1px solid green;
}
object{
  border: 1px solid blue;
}
<img src="">
<object></object>
<div>Try to mouse hover the black rectangle in both the <code>&lt;img></code> and <code>&lt;object></code> tags.

<img>中基于脚本的动画.

这些根本行不通。 SVG 文档嵌入 <img>标签无法编写脚本。 要解决此问题,请使用 <object> ,一个<embed><iframe>元素作为容器。

var svgStr = `
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" width="50" height="50">
    <rect id="rect" x="0" y="0" width="30" height="50"/>
    <script type="application/javascript">  
      // will simply never work in img
      var x = 0, rect = document.getElementById('rect');
      function anim() {
        x = (x + 1) % 80;
        rect.setAttribute('x', x - 30);
        requestAnimationFrame(anim);
      }
      anim();
    <\/script>
  </svg>`;

loadSVG(document.images[0]);
loadSVG(document.querySelector('object'));

function loadSVG(container) {
  var url = URL.createObjectURL(new Blob([svgStr], {type: 'image/svg+xml'}));
  container.src = container.data = url;
}
img{
  border: 1px solid green;
}
object{
  border: 1px solid blue;
}
<img src="">
<object></object>

<小时/>

基本上,SVG 在<img>带有很多限制,使用其他容器都可以克服这些限制。
现在,每个容器都有自己的限制:

  • <iframe>不会根据其内容调整大小,默认情况下它还会带有边框和其他一些丑陋的东西。
  • <object><embed>当不可见时( display: none )将被 webkit 浏览器卸载,并且不会在任何浏览器中缓存...

当然,也可以通过 AJAX 获取 SVG 标记并将其加载到实际的 HTML 页面中,但我个人不建议这样做:

  • 您需要确保没有重复的 id 元素,
  • 您需要确保所有 CSS 规则足够具体,以免影响页面中的其他元素,
  • 您必须确保仅加载受信任的代码,因为脚本将会运行,也就是说您为 XSS 攻击敞开了大门。
<小时/>

既然我们在这里,SVG 的另一个限制在 <img>最大的问题是它无法加载自己标记之外的任何资源,所有内容都需要直接包含在其中,甚至包括字体和光栅图像。

关于javascript - 如何为未硬编码的 SVG 制作动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49584246/

相关文章:

javascript - dojofilteringSelect - 仅允许输入列表项

javascript - 在 Material-ui 按钮上调用 onClick 事件的 Action 创建者不起作用

javascript - 根据以像素为单位的偏移量在 DIV 中查找特定文本

javascript - 展开时将背景颜色应用于数据表行

Javascript 使用保留关键字作为键

python - 使用OpenCV检测并将一幅图像中的区域替换为另一幅图像

python - 如何验证两个图像完全相同?

javascript - 为什么 firstChild 不返回第一个元素?

javascript - textarea $watchscrollheight和scrolltop不触发更新

javascript - ajax成功后jQuery继续循环执行