使用 SVG 实现支付成功动画
前言
SVG(Scalable Vector Graphics)是一种基于 XML 的矢量图形格式,广泛用于 Web 开发,尤其适用于绘制图标、图表和动画效果。本篇文章将通过一个支付成功动画的示例,介绍 SVG 的基本概念和相关 API。
代码示例
下面是完整的 HTML 代码,该代码利用 SVG 创建一个支付成功的动画,包括一个进度圆圈、对号以及“支付成功”文字。
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>SVG 支付成功动画</title>
<style>
*{
margin: 0;
padding: 0;
}
body{
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<svg width="120" height="140" viewBox="0 0 120 140" xmlns="http://www.w3.org/2000/svg">
<circle cx="60" cy="60" r="50" fill="none" stroke="#eee" stroke-width="4" />
<circle cx="60" cy="60" r="50" fill="none" stroke="transparent" stroke-width="4" stroke-linecap="round"
stroke-dasharray="314 314" stroke-dashoffset="314" opacity="0">
<animate attributeName="opacity" from="0" to="1" dur="0.1s" begin="0s" fill="freeze" />
<animate attributeName="stroke" from="transparent" to="#00aa00" dur="0.1s" begin="0s" fill="freeze" />
<animate attributeName="stroke-dashoffset" from="314" to="0" id="circle" dur="2s" begin="0.1s" fill="freeze" />
</circle>
<path d="M45 55 L55 65 L75 45" fill="none" stroke="#00aa00" stroke-width="4" stroke-dasharray="42"
stroke-dashoffset="42">
<animate attributeName="stroke-dashoffset" from="42" to="0" dur="0.5s" begin="circle.end" fill="freeze" />
<!-- id为circle.end结束开始此动画 -->
</path>
<text x="60" y="85" text-anchor="middle" font-size="14" font-weight="bold" fill="#333" opacity="0"
dominant-baseline="middle">
支付成功
<animate attributeName="opacity" from="0" to="1" dur="0.5s" begin="2.5s" fill="freeze" />
</text>
</svg>
</body>
</html>
解析代码
1. 背景圆
<circle cx="60" cy="60" r="50" fill="none" stroke="#eee" stroke-width="4" />
cx
和cy
定义圆心坐标。r
是半径。fill="none"
让圆形透明,仅显示边框。stroke="#eee"
让圆的边框为灰色。stroke-width="4"
设定边框的宽度。
2. 进度圆动画
<circle cx="60" cy="60" r="50" fill="none" stroke="transparent" stroke-width="4" stroke-linecap="round"
stroke-dasharray="314 314" stroke-dashoffset="314" opacity="0">
stroke-dasharray="314 314"
使圆形成为一个完整的虚线环。stroke-dashoffset="314"
初始时整个圆被隐藏。animate
标签用于控制动画:opacity
动画让圆形渐显。stroke
动画改变边框颜色。stroke-dashoffset
让进度圆从无到完整。
3. 对号动画
<path d="M45 55 L55 65 L75 45" fill="none" stroke="#00aa00" stroke-width="4" stroke-dasharray="42"
stroke-dashoffset="42">
<animate attributeName="stroke-dashoffset" from="42" to="0" dur="0.5s" begin="circle.end" fill="freeze" />
</path>
d="M45 55 L55 65 L75 45"
定义对号的路径。stroke-dasharray="42"
让对号显示为虚线,长度 42。stroke-dashoffset="42"
初始时隐藏对号。animate
使stroke-dashoffset
从 42 变成 0,实现对号绘制动画。
4. 文字动画
<text x="60" y="85" text-anchor="middle" font-size="14" font-weight="bold" fill="#333" opacity="0"
dominant-baseline="middle">
支付成功
<animate attributeName="opacity" from="0" to="1" dur="0.5s" begin="2.5s" fill="freeze" />
</text>
text-anchor="middle"
让文字居中。opacity="0"
初始时文字隐藏。animate
让opacity
从 0 变为 1,实现淡入效果。
关键点总结
stroke-dasharray
和stroke-dashoffset
控制路径绘制动画。<animate>
使属性值随时间变化,实现动画。begin
属性用于控制动画播放顺序。
SVG 在 Web 动画领域有着广泛的应用,它能创建高质量、可缩放的动画,且性能优越,适用于多种场景。