把現實世界的物體搬進電腦裡模擬,其實並不新鮮。簡單的物理實驗、碰撞後的旋轉與反彈,難度都還在可控範圍內;真正棘手的向來是流體——水、煙、岩漿這類會自由變形、彼此擠壓的東西。本文就用 Canvas 做一個 2D 平面上的小水滴,示範如何靠純 JavaScript 拼出足以亂真的晃動效果。
牽涉到的知識點與技巧大致有三塊:JScex 的異步寫法、貝塞爾曲線的繪製,以及 CanvasRenderingContext2D 上 translate 與 rotate 這兩個座標變換 API。
動手之前得先想清楚:橢圓到底怎麼畫?常見思路大概有四種:
第四種效能最好,也最省事:不必自己跑一堆三角函數與開方運算,把重活交給 CanvasRenderingContext2D 的 API 就好。這些 API 經過嚴格測試,絕大多數情況下都值得信賴。
var canvas;
var ctx;
ctx = canvas.getContext("2d");
ctx.strokeStyle = "#fff";
function drawEllipse(x, y, w, h) {
var k = 0.5522848; // 用貝塞爾曲線逼近圓時的標準控制點比例
var ox = (w / 2) * k;
var oy = (h / 2) * k;
var xe = x + w;
var ye = y + h;
var xm = x + w / 2;
var ym = y + h / 2;
ctx.beginPath();
ctx.moveTo(x, ym);
ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
ctx.stroke();
}
drawEllipse(10, 10, 40, 82);
那個 0.5522848 看起來像亂數,其實是四段三次貝塞爾曲線擬合正圓時的固定係數,記住即可。試著改動 drawEllipse 的四個參數:當 w 與 h 不相等時得到橢圓,相等時幾乎就是正圓——注意,是「幾乎」。
這裡的旋轉指的是繞橢圓中心轉,而不是繞左上角那個 (x, y) 轉。麻煩的是 CanvasRenderingContext2D.rotate 的旋轉中心永遠固定在畫布原點 (0, 0),所以光呼叫 rotate 並不足夠。正確順序是:先用 translate 把原點搬到橢圓中心,然後再呼叫 drawEllipse(-a/2, -b/2, a, b)。
這一行組合就是「繞中心旋轉」的核心技巧,而且可以推廣到任何圖形或圖片——只要你事先約定好中心點落在哪裡。
有了這套基礎,我們就能先把一團「鳥巢」狀的線條畫出來:
<head>
<script src="https://files.cnblogs.com/iamzhanglei/JScex/JScex.JscexRequire.min.js" type="text/javascript"></script>
</head>
<body>
<style type="text/css">
input.CSS3btn {
background: -moz-linear-gradient(270deg, #d2ebf8, #0c8ab5);
background: -webkit-linear-gradient(top, #d2ebf8, #0c8ab5);
background: -o-linear-gradient(top, #d2ebf8, #0c8ab5);
border-top: 1px solid #38538c;
border-right: 1px solid #1f2d4d;
border-bottom: 1px solid #151e33;
border-left: 1px solid #1f2d4d;
border-radius: 4px;
box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d,
0 2px 0px #1f3053, 0 4px 4px 1px #111111;
color: #f0f0f0;
font: bold 20px "helvetica neue", helvetica, arial, sans-serif;
padding: 10px 0 10px 0;
text-align: center;
text-shadow: 0px -1px 1px #1e2d4d;
width: 150px;
background-clip: padding-box;
}
input.CSS3btn:hover { box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 3px 0px #1f3053, 0 4px 4px 1px #111111; cursor: pointer; }
input.CSS3btn:active { box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111; }
</style>
<canvas width="350" height="350" style="border: solid 15px #222; background-color: #111; color: #CCC;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas, ctx, px = 0, py = 0;
function init() {
ctx = canvas.getContext("2d");
ctx.strokeStyle = "#fff";
ctx.translate(70, 70);
}
init();
function drawEllipse(x, y, w, h) {
var k = 0.5522848;
var ox = (w / 2) * k, oy = (h / 2) * k;
var xe = x + w, ye = y + h;
var xm = x + w / 2, ym = y + h / 2;
ctx.beginPath();
ctx.moveTo(x, ym);
ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
ctx.stroke();
ctx.translate(x + 70, y + 100);
px = -70;
py = -100;
ctx.rotate(10 * Math.PI * 2 / 360);
}
var ct;
var drawAsync = eval(JScex.compile("async", function (ct) {
while (true) {
drawEllipse(px, py, 140, 200);
$await(JScex.Async.sleep(200, ct));
}
}));
function Button1_onclick() { ct.cancel(); }
function Button2_onclick() {
ct = new JScex.Async.CancellationToken();
drawAsync(ct).start();
}
</script>
<br />
<input type="button" value="run" onclick="return Button2_onclick()" />
<input type="button" value="stop" onclick="return Button1_onclick()" />
</body>
這裡用 JScex 把「無限迴圈加計時器」寫成接近同步的形式,讀起來比一堆巢狀 callback 舒服得多,同時保留了 CancellationToken 讓我們能隨時中止動畫。
旋轉的橢圓、鳥巢般的線條,跟水滴到底有什麼關係?關鍵就在於:把長軸與短軸調得非常接近,但不要真的相等(例如長軸 42、短軸 40),然後每畫一幀就旋轉一點點並清空畫布。這兩三個像素的落差會隨角度不斷錯位重疊,視覺上就成了水波盪漾似的晃動。
清空畫布的方式也得跟著調整。由於畫布已經被 rotate 過、原點也被 translate 移走了,原本那句 clearRect(0, 0, canvas.width, canvas.height) 已經清不到實際內容,必須換成涵蓋四個方向的更大範圍:
ctx.clearRect(-canvas.width, -canvas.height, 2 * canvas.width, 2 * canvas.height);
接著畫一個長軸 42、短軸 40 的橢圓,旋轉並清屏:
function drawEllipse(x, y, w, h) {
ctx.clearRect(-canvas.width, -canvas.height, 2 * canvas.width, 2 * canvas.height);
var k = 0.5522848;
var ox = (w / 2) * k, oy = (h / 2) * k;
var xe = x + w, ye = y + h;
var xm = x + w / 2, ym = y + h / 2;
ctx.beginPath();
ctx.moveTo(x, ym);
ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
ctx.stroke();
ctx.translate(x + 20, y + 21);
px = -20;
py = -21;
ctx.rotate(10 * Math.PI * 2 / 360);
}
var ct;
var drawAsync = eval(JScex.compile("async", function (ct) {
while (true) {
drawEllipse(px, py, 40, 42);
$await(JScex.Async.sleep(10, ct));
}
}));
結果會是什麼樣子?可以參考原作者當年的線上示範:
https://www.cnblogs.com/iamzhanglei/archive/2011/12/12/2284188.html
到這一步,畫面上出現的就是一顆不斷輕輕晃動的水珠了。整個效果沒有任何位圖素材,全靠四段貝塞爾曲線加上一點座標變換的巧思——這也正是 Canvas 有意思的地方。