物理動畫模擬真實世界物理規律(如重力、彈性、碰撞)。核心思想:將動作拆分為極小的時間步長,每幀更新位置、速度,視覺上形成流暢動畫。
<!DOCTYPE HTML>
<html>
<head>
<title>Tear Cloth Demo</title>
<link rel="stylesheet" type="text/css" href="tearCloth.css" />
</head>
<body>
<canvas id="c"></canvas>
<div id="info">
<div id="top"><a id="close" href="">close</a></div>
<p>- Tear the cloth with your mouse.<br><br>
- Right click and drag to cut the cloth<br><br>
- Reduce physics_accuracy if it's laggy.</p>
</div>
<script src="tearCloth.js"></script>
</body>
</html>
* { margin:0; overflow:hidden; user-select:none; }
body, canvas { background:#333; }
canvas { width:100%; height:376px; display:block; }
#info { position:absolute; left:-1px; top:-1px; max-width:380px; background:#f2f2f2; border-bottom-right-radius:10px; }
#top { background:#fff; border-bottom:1px solid #eee; }
p { font-family:Arial; color:#666; font-size:16px; margin:10px; text-align:justify; }
a { font-family:sans-serif; color:#444; font-size:20px; text-decoration:none; }
#close { float:right; margin:10px; }
關鍵參數配置:
var physics_accuracy = 6, // 物理迭代精度
mouse_influence = 20, // 滑鼠影響半徑
mouse_cut = 5, // 剪切半徑(右鍵)
gravity = 900, // 重力加速度
cloth_height = 30, // 窗布網格高度
cloth_width = 50, // 窗布網格寬度
spacing = 7, // 節點間距
tear_distance = 60; // 撕裂距離閾值
核心類結構:
tear_distance 斷裂。動畫循環:
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
cloth.update(); // 解約束、更新位置
cloth.draw(); // 繪製所有約束線段
requestAnimFrame(update);
}
若需快速構建類似效果,verlet-js 是輕量級 JavaScript 物理引擎,基於 Verlet 積分法。