SVG路径动画

SVG路径动画

SVG路径动画,先用定义路径,再利用关键帧动画控制路径上的css属性。但如果想让某个片段沿着轨迹移动,这里记录两种方式。

一、利用svg属性

path可以看作一条虚线绘制的路径,有两个属性可以定义虚线的样式以及虚线间偏移距离。

stroke-dasharray: 样式,可以设置虚线线段的长度和线段的间距。

stroke-dashoffset:偏移值。

轨迹动画就是定义出虚线,然后关键帧控制偏移值改变,从而达到轨迹运动。

代码如下:

<!doctype html>
<html>
<head>
	<title>SVG Animate</title>
</head>
<style>
body {
	 100vw;
	height: 100vh;
	position: relative;
}
svg {
	 100%;
	height: 100%;
}
.move {
    stroke-dasharray: 16 100%;
    stroke-dashoffset: 320;
    animation: move 1.5s linear normal infinite;
}

@keyframes move {
	from {
	  stroke-dashoffset: 104%;
	  stroke: #00f;
	}
	to {
	  stroke-dashoffset: 65%;
	  stroke: #f00;
	}
}
</style>
<body>
	<svg version="1.1">
        <path fill="none" stroke="#eee" stroke-width="4" d="M 366,495 C 694.1,544.5 567.9,445.5 896,495"></path>
		<path fill="none" stroke="#f00" stroke-width="4" d="M 366,495 C 694.1,544.5 567.9,445.5 896,495" class="move"></path>
	</svg>
</body>
</html>

二、使用标签偏移属性

标签有offset-pathoffset-distance两个属性。一个定义该标签偏移路径,一个定义偏移距离。

该方案与svg属性类似,用关键帧控制路径偏移,达到动画效果

<!doctype html>
<html>
<head>
	<title>SVG Animate</title>
</head>
<style>
body {
	 100vw;
	height: 100vh;
	position: relative;
}
svg {
	 100%;
	height: 100%;
}
.move {
    stroke-dasharray: 16 100%;
    stroke-dashoffset: 320;
    animation: move 1.5s linear normal infinite;
}

@keyframes move {
	from {
	  stroke-dashoffset: 104%;
	  stroke: #00f;
	}
	to {
	  stroke-dashoffset: 65%;
	  stroke: #f00;
	}
}

#run {
	 16px;
	height: 16px;
	top: 0;
	left: 0;
	position: absolute;
	border-radius: 50%;
	background: #4a90e2;
	offset-path: path('M 366,495 C 694.1,544.5 567.9,445.5 896,495');
	offset-distance: 0%;
	animation: run 3s ease-in-out alternate infinite;
}
@keyframes run {
	from {
	  offset-distance: 100%;
	}
	to {
	  offset-distance: 0%;
	}
}
</style>
<body>
	<svg version="1.1">
		<path fill="none" stroke="#eee" stroke-width="4" d="M 366,495 C 694.1,544.5 567.9,445.5 896,495"></path>
		<path fill="none" stroke="#f00" stroke-width="4" d="M 366,495 C 694.1,544.5 567.9,445.5 896,495" class="move"></path>
	</svg>
	<div id="run"></div>
</body>
</html>
敌人总是会在你最不想它出现的地方出现!
原文地址:https://www.cnblogs.com/longhx/p/15741323.html