位置、缩放、旋转是物体三个常用属性。由于THREE.Mesh基础自THREE.Object3D,因此包含scale、rotation、position三个属性。它们都是THREE.Vector3实例,因此修改其值的方法是相同的,这里以位置为例。
THREE.Vector3有x、y、z三个属性,如果只设置其中一个属性,则可以用以下方法:
mesh.position.z = 1;
如果需要同时设置多个属性,可以使用以下两种方法:
mesh.position.set(1.5, -0.5, 0);
或者:
mesh.position = new THREE.Vector3(1.5, -0.5, 0);
缩放对应的属性是scale,旋转对应的属性是rotation,具体方法与上例相同,分别表示沿x、y、z三轴缩放或旋转。
源码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>3.js测试9.3</title> </head> <body> <canvas ></canvas> </body> <script type="text/javascript" src="https://www.jb51.net/js/three.min.js"></script> <script type="text/javascript"> function init() { var renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('mainCanvas') }); renderer.setClearColor(0x000000); var scene = new THREE.Scene(); // camera var camera = new THREE.OrthographicCamera(-2.5, 2.5, 1.875, -1.875, 0.1, 100); camera.position.set(5, 5, 20); camera.lookAt(new THREE.Vector3(0, 0, 0)); scene.add(camera); var material = new THREE.MeshLambertMaterial({ color: 0xffff00 }); var geometry = new THREE.CubeGeometry(1, 2, 3); var mesh = new THREE.Mesh(geometry, material); scene.add(mesh); mesh.position.set(1.5, -0.5, 0); mesh.position = new THREE.Vector3(1.5, -0.5, 0); mesh.position.z = 1; var light = new THREE.DirectionalLight(0xffffff); light.position.set(20, 10, 5); scene.add(light); drawAxes(scene); // render renderer.render(scene, camera); } function drawAxes(scene) { // x-axis var xGeo = new THREE.Geometry(); xGeo.vertices.push(new THREE.Vector3(0, 0, 0)); xGeo.vertices.push(new THREE.Vector3(1, 0, 0)); var xMat = new THREE.LineBasicMaterial({ color: 0xff0000 }); var xAxis = new THREE.Line(xGeo, xMat); scene.add(xAxis); // y-axis var yGeo = new THREE.Geometry(); yGeo.vertices.push(new THREE.Vector3(0, 0, 0)); yGeo.vertices.push(new THREE.Vector3(0, 1, 0)); var yMat = new THREE.LineBasicMaterial({ color: 0x00ff00 }); var yAxis = new THREE.Line(yGeo, yMat); scene.add(yAxis); // z-axis var zGeo = new THREE.Geometry(); zGeo.vertices.push(new THREE.Vector3(0, 0, 0)); zGeo.vertices.push(new THREE.Vector3(0, 0, 1)); var zMat = new THREE.LineBasicMaterial({ color: 0x00ccff }); var zAxis = new THREE.Line(zGeo, zMat); scene.add(zAxis); } </script> </html>