要在二維空間裡做出三維的錯覺,關鍵就是把 (x, y, z) 轉換成 (x, y)。最基本的生活經驗是:越遠的東西看起來越小,而且越靠近畫面中央的消失點。
對應的透視公式非常簡短:
scale = fl / (fl + z);
其中 scale 是縮放比例,落在 0.0 到 1.0 之間;fl 是觀察點到成像平面的距離,通常是固定值;z 是物件在三維空間中的 z 軸座標。
這個公式的行為很直觀:z 為 0 時 scale 等於 1(原尺寸);z 越大(越遠)分母越大,scale 越小;z 趨近無限遠時 scale 趨近 0,物件縮成一個點——那就是消失點。
寫這類程式之前,我習慣先用物件思維把結構想清楚:
這個責任劃分很重要。如果讓每個物件自己算投影,那麼「觀察點在哪裡」這件事就會散落在各處;集中到場景裡,只要改一個地方就能調整視角。
除了位置與大小,還有一個不能忽略的問題:誰該畫在前面? 答案是 z 值小的(近的)要後畫,這樣才會覆蓋在遠的物件上面。實作上把所有物件依 z 排序(通常是由遠到近),再依序繪製即可。這就是所謂的画家演算法。
下列示範可用滑鼠移動與滾輪操作,分別對應視角的水平/垂直旋轉與前後推進:
效果 1
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>偽 3d 透視效果</title>
<style>
html,body{ padding:0px; margin:0px; height:100%; width:100%;overflow:hidden;}
#box{ background:#ccc; height:100%; border:1px solid #ccc;position:relative; overflow:hidden;}
#debug{ width:200px; background:#fff; border:1px solid #ccc; position:absolute; left:10px; top:0px;}
</style>
</head>
<body>
</body>
</html>
效果 2
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>偽 3d 透視效果</title>
<style>
html,body{ padding:0px; margin:0px; height:100%; width:100%;overflow:hidden;}
#box{ background:#ccc; height:100%; border:1px solid #ccc;position:relative; overflow:hidden;}
#debug{ width:200px; background:#fff; border:1px solid #ccc; position:absolute; left:10px; top:0px;}
</style>
</head>
<body>
</body>
</html>
效果 3
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>偽 3d 透視效果</title>
<style>
html,body{ padding:0px; margin:0px; height:100%; width:100%;overflow:hidden;}
#box{ background:#fff; height:100%; border:1px solid #ccc;position:relative; overflow:hidden;}
#debug{ width:200px; background:#fff; border:1px solid #ccc; position:absolute; left:10px; top:0px;}
</style>
</head>
<body>
</body>
</html>
效果 4
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>偽 3d 透視效果</title>
<style>
html,body{ padding:0px; margin:0px; height:100%; width:100%;overflow:hidden;}
#box{ background:#ccc; height:100%; border:1px solid #ccc;position:relative; overflow:hidden;}
#debug{ width:200px; background:#fff; border:1px solid #ccc; position:absolute; left:10px; top:0px;}
</style>
</head>
<body>
</body>
</html>
這個「偽 3D」思路到今天仍然很有價值。理解透視投影之後,幾個自然的下一步是:
而如果只是想快速做出一點層次感,現在也可以直接用 CSS 的 transform: translate3d() 搭配 perspective,讓瀏覽器幫你處理投影。但自己刻過一次公式,你才知道那些屬性背後在做什麼。