今天郭先生來說一說three.js的一個圖形用戶界面工具gui,如下圖,在線案例點擊博客原文
1. 引入GUI,構造函數
按照所需,引入的方式也不相同。
//通過script標簽引入 <script src="../libs/dat.gui.js"></script> var gui = new dat.GUI(); //通過npm引入 import { GUI } from "three/examples/jsm/libs/dat.gui.module"; var gui = new GUI();
2. 創建參數對象
var params = new function() { this.color = 0x00ff00; //顏色 this.length = 10; //幾何體的大小 this.size = 0.3; //粒子大小 this.state = 'sphere'; //默認幾何體 this.states = ['sphere', 'cube']; //幾何體種類 this.visible = true; //是否顯示幾何體 };
3. Model和View的交互
首先說說gui的一些方法
方法 | 介紹 |
---|---|
add | 添加一個表單組件,參數依次為(對象,屬性,最小值,最大值) |
addColor | 添加一個顏色選擇面板,參數依次為(對象,屬性) |
addFolder | 添加一個欄目,參數為欄目的名稱,該函數返回一個對象,這個對象仍然可以使用add()、addColor()、addFolder()方法 |
gui組件有單選框,滑塊,下拉列表等,渲染那種組件取決於params的參數,下面是代碼示例
gui.addColor(params, "color").onChange(e => { //點擊顏色面板,e為返回的10進制顏色 pointsMaterial.color.set(e); }); gui.add(params, "length", 8, 30).onChange(e => { //該滑塊的值域是[8,30],e為返回的滑塊值 if(params.state == 'sphere') { objGeometry = new THREE.SphereGeometry(e, 30, 18); } else { objGeometry = new THREE.BoxGeometry(params.length * 1.5, params.length * 1.5, params.length * 1.5, 10, 10, 10); } points.geometry.vertices = objGeometry.vertices; points.geometry.verticesNeedUpdate = true; }) gui.add(params, "size", 0.1, 1).onChange(e => { //同上 pointsMaterial.size = e }); gui.add(params, "state").options(params.states).onChange( e => { //這是一個下拉列表,state是默認值,列表項通過options設置,params.states為列表數組,e返回所選的列表項。 scene.remove(scene.getObjectByName('points')); if(e == 'sphere') { objGeometry = new THREE.SphereGeometry(params.length, 30, 18); } else { objGeometry = new THREE.BoxGeometry(params.length * 1.5, params.length * 1.5, params.length * 1.5, 10, 10, 10); } geometry = new THREE.Geometry(); geometry.vertices = objGeometry.vertices; points = new THREE.Points(geometry, pointsMaterial); points.name = 'points'; scene.add(points); }) gui.add(params, 'visible').onChange(e => { //這是一個單選框,因為params.visible是一個布爾值,e返回所選布爾值 points.visible = e; })
gui就說到這里,希望大家靈活運用。
轉載請注明地址:郭先生的博客