這個範例示範了 SVG 的 <animate> 標籤能有多強:完全不用 JavaScript,只靠路徑變形動畫,就能畫出一個蛋糕從無到有、奶油擠上、蠟燭點燃的完整過程,最後跳出「生日快樂」。
線上預覽:https:///keleyi/phtml/html5/29.htm(請使用支援 HTML5 的瀏覽器開啟)
整個畫面由三大區塊組成:
<div class="velas"> 裡面放了五個 <div class="fuego">,用 CSS 動畫讓火苗跳動。<div class="text"> 包著 <h1>生日快樂!</h1>。<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML5/CSS3 生日蛋糕動畫</title><base target="_blank" />
<link rel="stylesheet" href="https:///keleyi/phtml/html5/29/css/reset.css">
<link rel="stylesheet" href="https:///keleyi/phtml/html5/29/css/style.css" media="screen" type="text/css" />
</head>
<body>
<div class="velas">
<div class="fuego"></div>
<div class="fuego"></div>
<div class="fuego"></div>
<div class="fuego"></div>
<div class="fuego"></div>
</div>
<svg id="cake" version="1.1" x="0px" y="0px" width="200px" height="500px" viewbox="0 0 200 500"
enable-background="new 0 0 200 500" xml:space="preserve">
<!-- 蛋糕各層路徑,每個 path 內含 animate 元素 -->
</svg>
<div class="text">
<h1>生日快樂!</h1>
<p></p>
</div>
<div style="text-align:center;clear:both">
<a href="https://">首頁</a> <a href="https:///keleyi/phtml/">特效庫</a>
<a href="https:///a/bjae/ll6aldf2.htm">原文</a>
請使用<a href="https:///a/bjac/g039tue3.htm">支援 HTML5 的瀏覽器</a>查看本頁。
</div>
</body>
</html>
每一層蛋糕都是一個 <path>,裡面放一個 <animate>,動畫的關鍵在兩個屬性:
<path fill="#a88679" d="M173.667-13.94c-49.298,0-102.782,0-147.334,0...">
<animate id="bizcocho_3" attributename="d" calcmode="spline"
keysplines="0 0 1 1; 0 0 1 1" begin="relleno_2.end" dur="0.3s" fill="freeze"
values="
M173.667-13.94c-49.298,0-102.782,0-147.334,0... ;
M173.667,411.567c-47.995,12.408-102.955,12.561-147.334,0... ;
M173.667,427.569c-49.795,0-101.101,0-147.334,0...
" />
</path>
要點說明:
奶油(crema)那段使用了更多的 values 關鍵幀,讓擠出來的形狀先堆高、再攤開、最後出現不規則的擠花邊緣,是全段動畫裡最費工的部分。
svg 中每個 path 的 values 都是動畫的靈魂,但手寫大量路徑座標非常費神。實務上的做法是用 Illustrator、Inkscape 或 Figma 畫好各階段的形狀,匯出 SVG 後再手動把 d 屬性值搬進 values 裡,並用分號串接。若想避開這道工序,也可以改用 CSS 的 transform 與 keyframes 做位移、縮放與旋轉組合,雖然畫不出「形狀變形」的效果,但開發速度快得多。
完整的 SVG 路徑動畫資料相當長,可於上方預覽頁的原始碼中取得全部內容。