重新启动背景SVG动画

重新启动背景SVG动画

本文介绍了重新启动背景SVG动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个SVG设置为元素的背景图片。第一次显示元素时,动画可以正常播放。

I have an SVG set as a background image of an element. The first time the element is displayed, the animation plays correctly.

在后续显示中(例如,如果元素的副本通过JavaScript注入,删除并添加回CSS / JavaScript),动画不从头开始。我认为这是预期的功能,因为图像不被认为已被浏览器重新加载 - 它使用已经动画的内存版本。

On subsequent displays (e.g. if a duplicate of the element is injected via JavaScript, or if the background image is removed and added back with CSS/JavaScript), the animation does not start from the beginning. I think this is intended functionality as the image is not considered to have been reloaded by the browser - it uses the in memory version which is already animating.

这里是一个演示(不是我的):

Here is a demo of this (not mine):http://www.luigifab.info/public/svg-smil/test.html

和,但如上所述

有没有办法让我的SVG动画在显示图片时重置/重播?

Is there any way to get my SVG animation to reset/replay whenever the image is displayed?

我理想地寻找一个只使用CSS和SVG的解决方案 - 如果这是不可能的解决方案,如果这是不可能的。

I'm ideally looking for a solution using just CSS and SVG - else a solution with JavaScript if this is not possible.

推荐答案

我想你的猜测...因为图像不被视为已被浏览器重新加载 - 它使用已经是动画的内存版本是正确的,因为SVG文件被缓存!因此,没有(真实的)'重新加载'动画不被触发(再次)。

I think your guess "... as the image is not considered to have been reloaded by the browser - it uses the in memory version which is already animating" is correct, as the SVG file is cached! So without a (real) 'reload' the animation is not triggered (again).

首先让我们来看看SVG动画。您可以在动画元素中使用两个属性来重复动画 - 请参阅和 。在你的情况下,动画只运行一次(不重复)。

Well, firstly let's have a look at SVG animations. There are two attributes you can use inside an animation element which are used to repeat the animation - see Repeating Animations and The ‘animate’ element. In your case the animation runs only once (no repetition).

所以你需要Javascript来以某种方式触发动画。

可能原则上(例如:),但仅当SVG文件是DOM的一部分,您可以通过Javascript访问。因此,您必须将SVG文件包含为< object>

So you would need Javascript to somehow "trigger" the animation.
This is possible in principle (example: Advanced SVG Animation Techniques), but only if the SVG file is part of the DOM, which you can access via Javascript. Therefor you have to include the SVG file as an <object>.

< img> 标记中或作为CSS background-image ,您没有脚本访问该文件。

As soon as you use a SVG file in an <img> tag or as a CSS background-image you have no script access to the file.

因此,我想到的唯一的方法就是阻止浏览器缓存SVG文件(参见),或使用SVG文件在< object> code>元素,以便您可以通过Javascript控制动画。

So the only way I could think of to achieve your goal is to prevent the browser from caching the SVG file (see How (and how not) to Control Caches), or to use the SVG file in an <object> element so that you can control the animation via Javascript.

BTW:luigifab的答案不是那么糟糕。这是一个经常使用的伎俩,强制重新加载文件/图片 - 请参见

BTW: luigifab's answer is not that bad. This is an often used "trick" to force reload of a file/ an image - see The Cache Trick

这篇关于重新启动背景SVG动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 14:36