svg实现根据轨迹滑动

192 阅读1分钟

ScreenGif.gif

如何实现,当选中一个节点,元素在曲线轨迹滑动的动画效果?

利用svg中的mpath元素,

mpath元素定义: 元素的mpath子元素使 元素能够引用一个外部的元素作为运动路径的定义。

animateMotion元素定义:定义了一个元素如何沿着运动路径进行移动,可以设置动画的时间等属性。

核心原理:利用曲线(path)的id和mpath中的xlink:href的值对应,实现动画效果。

片段一:设置滑动的小球

			var shape_circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
			shape_circle.setAttribute("r", 4);
			shape_circle.setAttribute("fill", "blue");
			shape_circle.setAttribute("opacity", 0.8);
			shape_circle.setAttribute("id", "circle_" + linkId);
			shape_circle.setAttribute("class", "circle-flow");

片段二:设置animateMotion

			var shape_animateMotion = document.createElementNS("http://www.w3.org/2000/svg", "animateMotion");
			shape_animateMotion.setAttribute("dur", "3s");
			shape_animateMotion.setAttribute("repeatCount", "indefinite");
			shape_animateMotion.setAttribute("begin", "0s");
			shape_circle.appendChild(shape_animateMotion);

片段三:设置mpath,此处要注意xlink:href是需要指定命名空间的,当动态生成dom一定要通过setAttributeNS设置才生效

			var shape_mpath = document.createElementNS("http://www.w3.org/2000/svg", "mpath");
			shape_mpath.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + linkId);
			shape_animateMotion.appendChild(shape_mpath);

全部代码

//linkId为曲线id值;group为svg元素
setCircle(linkId,group) {
			var shape_circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
			shape_circle.setAttribute("r", 4);
			shape_circle.setAttribute("fill", "blue");
			shape_circle.setAttribute("opacity", 0.8);
			shape_circle.setAttribute("id", "circle_" + linkId);
			shape_circle.setAttribute("class", "circle-flow");

			var shape_animateMotion = document.createElementNS("http://www.w3.org/2000/svg", "animateMotion");
			shape_animateMotion.setAttribute("dur", "3s");
			shape_animateMotion.setAttribute("repeatCount", "indefinite");
			shape_animateMotion.setAttribute("begin", "0s");
			shape_circle.appendChild(shape_animateMotion);

			var shape_mpath = document.createElementNS("http://www.w3.org/2000/svg", "mpath");
			shape_mpath.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + linkId);
			shape_animateMotion.appendChild(shape_mpath);

			group.appendChild(shape_circle);
		}