本篇我們來介紹 ShapeGeometry 幾何體。通過前兩篇的介紹,我們會發現 PlaneGeometry 和 CircleGeometry 都只有有限的方法來定製他們的外觀。如果我們想創建一個自定義的二維圖形,那麼就只能依靠今天要講的 ShapeGeometry 了。
爲了使用 ShapeGeometry,我們首先需要通過 THREE.Shape 創建一個自定義的基本形狀,然後把它作爲參數傳遞給 ShapeGeometry 構造函數。因此,我們先來看看如何使用 THREE.Shape 創建自定義的基本形狀,代碼片段如下:
function drawShape() {
var shape = new THREE.Shape();
shape.moveTo(10, 10); // moveTo( x, y )
shape.lineTo(10, 40); // lineTo( x, y ) - 線
shape.bezierCurveTo(15, 25, 25, 25, 30, 40); // bezierCurveTo( cp1X, cp1Y, cp2X, cp2Y, x, y ) - 貝塞爾曲線
shape.splineThru([
new THREE.Vector2(32, 30),
new THREE.Vector2(28, 20),
new THREE.Vector2(30, 10)
]); // splineThru ( vector2Array ) - 樣條線
shape.quadraticCurveTo(20, 15, 10, 10); // quadraticCurveTo( cpX, cpY, x, y ) - 二次曲線
var hole = new THREE.Path(); // 添加“眼睛”孔洞1
hole.absellipse(16, 24, 2, 3, 0, Math.PI * 2, false);
shape.holes.push(hole);
hole = new THREE.Path(); // 添加“眼睛”孔洞2
hole.absellipse(23, 24, 2, 3, 0, Math.PI * 2, false);
shape.holes.push(hole);
hole = new THREE.Path(); // 添加“嘴巴”孔洞
hole.absarc(20, 16, 2, 0, Math.PI, false);
shape.holes.push(hole);
return shape;
}
在這段代碼裏,你可以看到我們用線段(line)、曲線(curve)和樣條線(spline)創建出圖像的輪廓,然後用 THREE.Shape 類的 holes(孔洞)屬性添加了幾個洞(兩隻眼睛,一張嘴巴)。下表列出了 THREE.Shape 類用來創建圖形的繪圖函數:
函數名 | 描述 |
---|---|
moveTo(x, y) | 將繪圖點移動到指定的 x、y 座標處 |
lineTo(x, y) | 從當前位置(例如 moveTo 設定的位置)畫一條線到指定的 x、y 座標處 |
quadricCurveTo(cpx, cpy, x, y) (二次曲線) |
此函數爲二次曲線。你可以使用兩種方法來畫曲線:quadricCurveTo 或者 bezierCurveTo。這兩種曲線的不同之處在於指定曲線曲率的方法不一樣,如下圖所示: 對於三次曲線,除了指定結束點(x, y)外,還需要額外指定兩個點(cpx1, cpy1, cpx2, cpy2)來控制曲線的曲率。 |
bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x, y) (貝塞爾曲線) |
此函數爲三次曲線。相關說明參考上一行的二次曲線。 |
splineThru(vector2Array) | 此函數沿着參數指定的座標集合繪製一條光滑的樣條曲線。其參數爲一個 THREE.Vector2 對象數組。 |
arc(x, y, radius, startAngle, endAngle, clockwise) | 次函數繪製一個圓或者一段弧。x, y 用來指定圓心與當前位置的偏移量。radius 設定圓的大小。而 startAngle 及 endAngle 則用來定義圓弧要畫多長。布爾屬性 clockwise 決定這段弧是順時針畫還是逆時針畫。 |
absArc(x, y, radius, startAngle, endAngle, clockwise) | 參考 arc 函數。只不過其指定的圓心位置是絕對位置,而不是相對當前位置的偏移量。 |
ellipse(x, y, radiusX, radiusY, startAngle, endAngle, clockwise) | 參考 arc 函數。只是橢圓可以分別指定 x 軸半徑及 y 軸半徑。 |
absEllipse(x, y, radiusX, radiusY, startAngle, endAngle, clockwise) | 參考 ellipse 函數。只不過其指定的圓心位置是絕對位置,而不是相對當前位置的偏移量。 |
在繼續討論之前,我們先給出一個完整的示例,代碼如下:
<!DOCTYPE html>
<html>
<head>
<title>示例 05.03 - ShapeGeometry</title>
<script src="../build/three.js"></script>
<script src="../build/js/controls/OrbitControls.js"></script>
<script src="../build/js/libs/stats.min.js"></script>
<script src="../build/js/libs/dat.gui.min.js"></script>
<script src="../jquery/jquery-3.2.1.min.js"></script>
<style>
body {
/* 設置 margin 爲 0,並且 overflow 爲 hidden,來完成頁面樣式 */
margin: 0;
overflow: hidden;
}
/* 統計對象的樣式 */
#Stats-output {
position: absolute;
left: 0px;
top: 0px;
}
</style>
</head>
<body>
<!-- 用於 WebGL 輸出的 Div -->
<div id="webgl-output"></div>
<!-- 用於統計 FPS 輸出的 Div -->
<div id="stats-output"></div>
<!-- 運行 Three.js 示例的 Javascript 代碼 -->
<script type="text/javascript">
var scene;
var camera;
var render;
var webglRender;
//var canvasRender;
var controls;
var stats;
var guiParams;
var ground;
//var cube;
//var sphere;
var plane;
var meshMaterial;
var ambientLight;
var spotLight;
//var cameraHelper;
$(function() {
stats = initStats();
scene = new THREE.Scene();
webglRender = new THREE.WebGLRenderer( {antialias: true, alpha: true} ); // antialias 抗鋸齒
webglRender.setSize(window.innerWidth, window.innerHeight);
webglRender.setClearColor(0xeeeeee, 1.0);
webglRender.shadowMap.enabled = true; // 允許陰影投射
render = webglRender;
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 30, 1000); // 2147483647
camera.position.set(-45.5, 68.2, 90.9);
var target = new THREE.Vector3(10, 0 , 0);
controls = new THREE.OrbitControls(camera, render.domElement);
controls.target = target;
camera.lookAt(target);
$('#webgl-output')[0].appendChild(render.domElement);
window.addEventListener('resize', onWindowResize, false);
ambientLight = new THREE.AmbientLight(0x0c0c0c);
scene.add(ambientLight);
spotLight = new THREE.SpotLight(0xffffff);
spotLight.position.set(0, 30, 60);
spotLight.castShadow = true;
scene.add(spotLight);
//cameraHelper = new THREE.CameraHelper(spotLight.shadow.camera);
//scene.add(cameraHelper);
// 加入一個地面
var groundGeometry = new THREE.PlaneGeometry(100, 100, 4, 4);
var groundMaterial = new THREE.MeshBasicMaterial({color: 0x777777});
ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.rotation.set(-0.5 * Math.PI, 0, 0); // 沿着 X軸旋轉-90°
scene.add(ground);
// 定義 shape
var shape = drawShape();
// 材質
meshMaterial = [
new THREE.MeshNormalMaterial({side: THREE.DoubleSide}),
new THREE.MeshBasicMaterial({wireframe: true})
];
/** 用來保存那些需要修改的變量 */
guiParams = new function() {
this.rotationSpeed = 0.02;
this.addMesh = function() {
createMesh(shape);
};
this.addPoints = function() {
createLine(shape, false);
};
this.addSpacedPoints = function() {
createLine(shape, true);
};
}
/** 定義 dat.GUI 對象,並綁定 guiParams 的幾個屬性 */
var gui = new dat.GUI();
gui.add(guiParams, 'addMesh');
gui.add(guiParams, 'addPoints');
gui.add(guiParams, 'addSpacedPoints');
guiParams.addMesh();
renderScene();
});
/** 渲染場景 */
function renderScene() {
stats.update();
rotateMesh(); // 旋轉物體
requestAnimationFrame(renderScene);
render.render(scene, camera);
}
/** 初始化 stats 統計對象 */
function initStats() {
stats = new Stats();
stats.setMode(0); // 0 爲監測 FPS;1 爲監測渲染時間
$('#stats-output').append(stats.domElement);
return stats;
}
/** 當瀏覽器窗口大小變化時觸發 */
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
render.setSize(window.innerWidth, window.innerHeight);
}
/** 旋轉物體 */
var step = 0;
function rotateMesh() {
step += guiParams.rotationSpeed;
scene.traverse(function(mesh) {
if ((mesh instanceof THREE.Mesh || mesh instanceof THREE.Line) && mesh != ground) {
//mesh.rotation.x = step;
mesh.rotation.y = step;
//mesh.rotation.z = step;
}
});
}
function drawShape() {
var shape = new THREE.Shape();
shape.moveTo(10, 10); // moveTo( x, y )
shape.lineTo(10, 40); // lineTo( x, y ) - 線
shape.bezierCurveTo(15, 25, 25, 25, 30, 40); // bezierCurveTo( cp1X, cp1Y, cp2X, cp2Y, x, y ) - 貝塞爾曲線
shape.splineThru([
new THREE.Vector2(32, 30),
new THREE.Vector2(28, 20),
new THREE.Vector2(30, 10)
]); // splineThru ( vector2Array ) - 樣條線
shape.quadraticCurveTo(20, 15, 10, 10); // quadraticCurveTo( cpX, cpY, x, y ) - 二次曲線
var hole = new THREE.Path(); // 添加“眼睛”孔洞1
hole.absellipse(16, 24, 2, 3, 0, Math.PI * 2, false);
shape.holes.push(hole);
hole = new THREE.Path(); // 添加“眼睛”孔洞2
hole.absellipse(23, 24, 2, 3, 0, Math.PI * 2, false);
shape.holes.push(hole);
hole = new THREE.Path(); // 添加“嘴巴”孔洞
hole.absarc(20, 16, 2, 0, Math.PI, false);
shape.holes.push(hole);
return shape;
}
function createMesh(shape) {
scene.remove(plane);
var shapeGeometry = new THREE.ShapeGeometry(shape);
plane = new THREE.SceneUtils.createMultiMaterialObject(shapeGeometry, meshMaterial);
plane.castShadow = true;
plane.position.set(0, 0, 0);
scene.add(plane);
}
/** 從已有的 shape 中進行分段再得出新形狀 */
function createLine(shape, spaced) {
scene.remove(plane);
var newPoints;
var shapeGeometry;
if (spaced) {
newPoints = shape.getSpacedPoints(3); // 把整個 shape 路徑當做一個整體進行分段並得到一個點集
} else {
newPoints = shape.getPoints(10); // 分別把 shape 中的每一段路徑進行分段(此處爲 10 段)並得到一個點集
}
shapeGeometry = new THREE.Geometry();
newPoints.forEach(function(vec2){
shapeGeometry.vertices.push(new THREE.Vector3(vec2.x, vec2.y, 0));
});
plane = new THREE.Line(shapeGeometry, new THREE.LineBasicMaterial({color: 0xff3333,linewidth: 2}));
plane.castShadow = true;
plane.position.set(0, 0, 0);
scene.add(plane);
}
</script>
</body>
</html>
這個示例的效果如下所示:
函數 | 描述 |
---|---|
getPoints( divisions ) | 此函數將圖形轉換成一個點集。參數 divisions(分段數)定義返回點的數目,它會分別應用到 shape 路徑的每一個部分。 |
getSpacedPoints( divisions ) | 此函數也是將圖形轉換成一個點集。參數 divisions(分段數)定義返回點的數目,它會一次性應用到 shape 的整個路徑上。 |
shapeGeometry = new THREE.Geometry();
newPoints.forEach(function(vec2){
shapeGeometry.vertices.push(new THREE.Vector3(vec2.x, vec2.y, 0));
});
plane = new THREE.Line(shapeGeometry, new THREE.LineBasicMaterial({color: 0xff3333,linewidth: 2}));
未完待續···