天天看点

svg 绘制多边形渐变边框并填充渐变背景

以六边形为例

绘制一个60*69像素的六边形

根据坐标  points="30,1 60,17 60,52 30,69 1,52 1,17"

设置边框大小 stroke-width="1"

设置边框颜色  stroke="#03ffea"

设置填充颜色 fill="#0f8bf1"

<svg width="60" height="69">
    <polygon points="30,1  60,17 60,52 30,69 1,52 1,17" stroke="#03ffea" fill="#0f8bf1" stroke-width="1" />
</svg>
           

以上 绘制出一个有填充颜色且有边框的多边形 

接下来 设置边框的渐变

根据文档 得知 

linearGradient

元素用来定义线性渐变,用于图形元素的填充或描边

在svg标签内 增加linearGradient标签 用于设置渐变

ID一定要填写 在多边形标签内需要使用

代码如下

<svg width="64" height="73">
	<defs>
		<linearGradient id="linear" x1="0%" y1="0%" x2="0%" y2="100%">
			<stop offset="0%" stop-color="rgba(16,32,73,0)"/>
			<stop offset="50%" stop-color="rgba(8,68,158,0)"/>
			<stop offset="80%" stop-color="rgba(6,81,191,0.18)"/>
			<stop offset="100%"   stop-color="rgba(0,108,255,0.35)"/>
		</linearGradient>

		<linearGradient id="linear1" x1="0%" y1="0%" x2="0%" y2="100%">
			<stop offset="0%"   stop-color="#03ffea"/>
			<stop offset="100%" stop-color="#0f8bf1"/>
		</linearGradient>
	</defs>
	<polygon fill="url(#linear)" points="30,1  60,17 60,52 30,69 1,52 1,17" stroke="url(#linear1)" stroke-width="2" />
</svg>
           

以上 多边形渐变边框且渐变填充已绘制完成

按需要增加边框动画

<style>
	polygon{
		animation: strokeDefaultPoly 3s linear infinite alternate;
	}
	@keyframes strokeDefaultPoly {
		0% {
			stroke-dasharray: 0 50;
		}
		100% {
			stroke-dasharray: 500;
		}
	}
</style>
           

css 中 可以通过设置stroke-dasharray属性值 调整动画起始

以上。

希望这篇文章能对大家有所帮助