three.js 圖形使用者介面工具GUI
阿新 • • 發佈:2020-07-17
今天郭先生來說一說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就說到這裡,希望大家靈活運用。
轉載請註明地址:郭先生的部落格