天天看點

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屬性值 調整動畫起始

以上。

希望這篇文章能對大家有所幫助