前言
本專欄是基于rust和tauri,由于tauri是前、后端結合的GUI框架,既可以直接生成包含前端代碼的文件,也可以在已有的前端項目上集成tauri框架,將前端頁面化為桌面GUI。
發文平臺
CSDN
環境配置
系統:windows 10
平臺:visual studio code
語言:rust、javascript
庫:tauri2.0
概述
本文是基于tauri和threejs,將threejs創建的3D畫面在tauri的窗口中呈現。
本文的實現其實非常簡單,threejs本身就可以在瀏覽器渲染3D圖像,而tauri則可以結合前后端,將瀏覽器的頁面顯示在窗口中。
1、新建tauri項目
可以參考筆者之前的項目:
<Rust><GUI>rust語言GUI庫tauri體驗:前、后端結合創建一個窗口并修改其樣式
或者參考tauri官網的手冊:
https://tauri.app/zh-cn/start/create-project/
本文就不再贅述新建項目的相關內容了,我們假設已經創建完成,我們在public文件夾中新建一個網頁three.html,添加一個div:
<div class="container"><h1>threejs 3D演示</h1><div id="threejs-view"><canvas id="threejs-canvas"></canvas></div>
</div>
然后,我們在main.js中獲取html并顯示:
async function loadhtml(htmlpath,div){const response = await fetch(htmlpath);const template = await response.text();document.querySelector(div).innerHTML = template;}await loadhtml('../public/three.html','#app');
2、使用threejs顯示3D
然后,我們需要使用threejs來實現3D圖像的顯示:
import * as THREE from "three";
import {OrbitControls} from 'three/addons/controls/OrbitControls.js';
import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
//const view = document.getElementById('threejs-view');
const canvas = document.getElementById('threejs-canvas');
//
let scene,camera,renderer,group;
async function loadProcess(){initThreeJs();
}function initThreeJs(){scene = new THREE.Scene();camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );renderer = new THREE.WebGLRenderer({antialias:true,canvas});const w1 = canvas.clientWidth;const h1 = canvas.clientHeight;renderer.setSize( w1, h1 );//renderer.setSize( window.innerWidth, window.innerHeight );//canvas.appendChild(renderer.domElement);//const geometry = new THREE.SphereGeometry( 1.5, 32, 16,0,Math.PI*2,0,Math.PI );group = new THREE.Group();//線材質const lineMaterial = new THREE.LineBasicMaterial( { color: '#55aaff', transparent: true, opacity: 0.5 ,});//光材質group.add(new THREE.LineSegments(geometry,lineMaterial));const meshMaterial = new THREE.MeshPhongMaterial( { color: '#25b0f5', emissive: '#072534', side: THREE.DoubleSide, flatShading: true ,});group.add(new THREE.Mesh( geometry, meshMaterial ) );scene.add(group);//// 從上方照射的白色平行光,強度為 0.5。const lights = [];lights[ 0 ] = new THREE.DirectionalLight( 0xffffff, 3 );lights[ 1 ] = new THREE.DirectionalLight( 0xffffff, 3 );lights[ 2 ] = new THREE.DirectionalLight( 0xffffff, 3 );lights[ 0 ].position.set( 0, 200, 0 );lights[ 1 ].position.set( 100, 200, 100 );lights[ 2 ].position.set( - 100, - 200, - 100 );scene.add( lights[ 0 ] );scene.add( lights[ 1 ] );scene.add( lights[ 2 ] );//const controls = new OrbitControls( camera, renderer.domElement );camera.position.z = 5;controls.update();//function animate(){group.rotation.x += 0.005;group.rotation.y += 0.005;requestAnimationFrame(() => animate());renderer.render(scene, camera);}animate();}loadProcess();
我們來看下上面代碼運行后的演示: