更新 SVG 动画

Updating SVG animations

本文关键字:动画 SVG 更新      更新时间:2023-09-26

我的代码将形状向左移动,并在 2 秒内淡出,并在 1 秒后重复所有内容

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="636px" height="155px" version="1.1">
	<g id="canvas" transform="translate(0.5,0.5)">		
	</g>
</svg>
<script language="javascript">
	var svgNS = "http://www.w3.org/2000/svg";  
	var canvas = document.querySelector('#canvas');
	function svgElement(name, attributes) {
		var element = document.createElementNS(svgNS, name); //to create a circle, for rectangle use rectangle
		for (key in attributes)
			element.setAttribute(key, attributes[key]);
		return canvas.appendChild(element);
	}
	function render() {
		while (canvas.firstChild) canvas.removeChild(canvas.firstChild);
		svgElement('rect', {x:x, y:"20", width:"100",height:"100",style:"fill:blue"})
	}
	var x = 100
	render()
	var wait = 0
	function clock() {
		if (wait > 0) {
			wait -= 1
			if (wait == 0)
				x = 100
		} else {
			x -= 10
			if (x < 1) {
				svgElement('animate', {attributeType:"CSS", attributeName:"opacity", from:1, to:0, dur:"2s", fill:"freeze"})
				wait = 30
			} else
				render()
		}
		
	}
	
	setInterval(clock, 100)
</script>

问题是不透明度淡入淡出在第二次迭代中会立即出现。广场立即消失。

有一个动画时间线,在添加第一个动画时开始运行,然后继续运行。因此,您的第一个动画在时间 0 运行。

对于后续动画,时间线已超过 0,因此当它们从时间 0(未指定开始)开始时,它们会立即发生。

  • 一种解决方案(如下所示)是重置动画时间线。

  • 另一种方法是计算动画的正确开始值 - 例如,您可以通过调用canvas.parentNode.getCurrentTime来获取它。

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="636px" height="155px" version="1.1">
	<g id="canvas" transform="translate(0.5,0.5)">		
	</g>
</svg>
<script language="javascript">
	var svgNS = "http://www.w3.org/2000/svg";  
	var canvas = document.querySelector('#canvas');
	function svgElement(name, attributes) {
		var element = document.createElementNS(svgNS, name); //to create a circle, for rectangle use rectangle
		for (key in attributes)
			element.setAttribute(key, attributes[key]);
		return canvas.appendChild(element);
	}
	function render() {
		while (canvas.firstChild) canvas.removeChild(canvas.firstChild);
		svgElement('rect', {x:x, y:"20", width:"100",height:"100",style:"fill:blue"})
	}
	var x = 100
    var begin = 0
	render()
	var wait = 0
	function clock() {
		if (wait > 0) {
			wait -= 1
			if (wait == 0)
				x = 100
		} else {
			x -= 10
			if (x < 1) {
				svgElement('animate', {attributeType:"CSS", attributeName:"opacity", from:1, to:0, dur:"2s", fill:"freeze", begin:begin})
				wait = 30
				canvas.parentNode.setCurrentTime(0);
			} else
				render()
		}
		
	}
	
	setInterval(clock, 100)
</script>