<tauri><threejs><rust><GUI>基于tauri和threejs,实现一个3D图形浏览程序
前言
本专栏是基于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();
我们来看下上面代码运行后的演示: