記錄--uniapp微信小程式引入threeJs並導入模型

来源:https://www.cnblogs.com/smileZAZ/archive/2022/11/28/16932638.html
-Advertisement-
Play Games

這裡給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 前言 我的需求是使用uniapp寫微信小程式,在小程式中使用threeJs就行了,目前暫不考慮相容app什麼的。 1.引入小程式版的threejs庫實現 2.使用webview實現(推薦) 重點 我的建議是使用這個庫https://git ...


這裡給大家分享我在網上總結出來的一些知識,希望對大家有所幫助

前言

我的需求是使用uniapp寫微信小程式,在小程式中使用threeJs就行了,目前暫不考慮相容app什麼的。
1.引入小程式版的threejs庫實現
2.使用webview實現(推薦)

重點

我的建議是使用這個庫
https://github.com/deepkolos/three-platformize
為什麼?我試了uniapp推薦的和threejs-miniprogram這個小程式官方庫,都載入不出來我的obj模型。所有我推薦不要用obj模型最好,挺多都支持GLTF模型的,但是我不能改。

使用three-platformize載入obj模型的案例:

 核心代碼:

html:
<canvas type="webgl" id="webgl" style="width: 100vw; height: 100vh;" 
	@touchstart="touchStart" 
	@touchmove="touchMove" 
	@touchend="touchEnd"
/>
script:
<script>
	import * as THREE from 'three-platformize';
	import { WechatPlatform } from 'three-platformize/src/WechatPlatform';
	import { OBJLoader } from 'three-platformize/examples/jsm/loaders/OBJLoader';
	import { GLTFLoader } from 'three-platformize/examples/jsm/loaders/GLTFLoader';
	import {OrbitControls} from 'three-platformize/examples/jsm/controls/OrbitControls';
	export default {
		data() {
			return {
				canvas:null,
				camera:null,
				scene:null,
				renderer:null,
				model:null,
				controls:null,
				loopIndex:null
			}
		},
		onLoad() {

		},
		methods: {
			async init() { 
				const { canvas }= await this.getCanvas();
				this.canvas = canvas;
				const platform = new WechatPlatform(canvas); // webgl canvas
				platform.enableDeviceOrientation('game'); // 開啟DeviceOrientation
				THREE.PLATFORM.set(platform);
				this.platform = platform;
				this.renderModel();
		    },
			//獲取畫布
			async getCanvas(delay = 200) {
			  return new Promise((resolve, reject) => {
				const t = setTimeout(() => {
				  clearTimeout(t);
				  uni.createSelectorQuery().in(this)
					.select('#webgl')
					.fields({ node: true })
					.exec((res) => {
						console.log('res',res)
					  if (res && res[0] && res[0].node) {
						const canvas = res[0].node;
						resolve({ canvas });
					  } else {
						reject("獲取canvas失敗");
					  }
					});
				}, delay);
			  });
			},
			renderModel () {
				this.camera = new THREE.PerspectiveCamera(45, this.canvas.width / this.canvas.height, 0.25, 100);
				this.camera.position.set(- 5, 3, 10);
				this.camera.lookAt(new THREE.Vector3(0, 2, 0));
				this.scene = new THREE.Scene();
				this.scene.background = new THREE.Color(0xe0e0e0);
				this.scene.fog = new THREE.Fog(0xe0e0e0, 20, 100);
				this.clock = new THREE.Clock();
				// lights
				var light = new THREE.HemisphereLight(0xffffff, 0x444444);
				light.position.set(0, 20, 0);
				this.scene.add(light);
				// 改變外殼顏色
				var AmbientLight = new THREE.AmbientLight(0x815800); // 環境光
				this.scene.add(AmbientLight);
				// 平行光
				light = new THREE.DirectionalLight(0xffffff);
				light.position.set(0, 20, 10);
				this.scene.add(light);
				// // ground
				// var mesh = new THREE.Mesh(new THREE.PlaneBufferGeometry(2000, 2000), new THREE.MeshPhongMaterial({ color: 0x999999, depthWrite: false }));
				// mesh.rotation.x = - Math.PI / 2;
				// this.scene.add(mesh);
				// var grid = new THREE.GridHelper(200, 40, 0x000000, 0x000000);
				// grid.material.opacity = 0.6;
				// grid.material.transparent = true;
				// this.scene.add(grid);
				// model
				var loader = new OBJLoader();
				loader.load('http://localhost:8888/obj3/file.obj', (obj) => {
					console.log("obj+=")
					console.log(obj)
					// console.log(this.model)
					obj.position.set(0, -2, 0);//模型擺放的位置
					obj.scale.set(0.2, 0.2, 0.2);
					// this.model = obj;
					this.scene.add(obj);
				}, undefined, function (e) {
					console.log("模型載入錯誤")
					console.error(e);
				});
				// var loader = new GLTFLoader();
				// 	loader.load('https://dtmall-tel.alicdn.com/edgeComputingConfig/upload_models/1591673169101/RobotExpressive.glb', (gltf) => {
				// 		this.model = gltf.scene;
				// 		this.scene.add(this.model);
				// 	}, undefined, function (e) {
				// 		console.error(e);
		  //       });
				// var geometry = new THREE.BoxGeometry( 5, 5, 5 );
				// var material = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
				// var mesh = new THREE.Mesh( geometry, material );
				// this.scene.add(mesh);
		
				this.renderer = new THREE.WebGLRenderer({antialias: true });
				this.renderer.setPixelRatio(wx.getSystemInfoSync().pixelRatio);
				this.renderer.setSize(this.canvas.width, this.canvas.height);
				//this.renderer.outputEncoding = true;
				this.renderer.gammaFactor = 2.2;
		
				this.controls = new OrbitControls(this.camera, this.renderer.domElement );
				this.camera.position.set( 5, 5, 10 );
				this.animate();
			},
		animate() {
		        this.loopIndex = this.canvas.requestAnimationFrame(this.animate);
		        this.renderer.render(this.scene, this.camera);
		        this.controls.update();
		    },
		
		    touchStart(e) {
		        this.platform.dispatchTouchEvent(e);
		    },
		    touchMove(e) {
		        this.platform.dispatchTouchEvent(e);
		    },
		    touchEnd(e) {
		        this.platform.dispatchTouchEvent(e);
		    }
		},
		mounted() {
			this.$nextTick(()=>  {
			      this.init();
			    });
		}
	}
</script>

上面的案例中使用了兩個模型,一個obj模型,obj模型的地址是自己寫的本地伺服器地址,需要自己配置,GLTF模型地址是網路地址,可以把註釋解開查看。

註意點

1.載入外部模型與threeJs官網api是一致的
2.使用此方法載入外部模型,可能在真機調試時遇到模型不展示,或者微信閃退的情況(原因未知)

webview實現引入threejs庫

效果圖

實現:
1.使用vue實現threejs導入obj模型(pc端可完美實現),
2.在webview中引入相應的模型展示地址,

完結,就這兩步即可,但是我是動態載入,所以在載入模型的時候,你需要在小程式端傳值給pc端,讓pc端載入相應的模型,這裡就只需要用get在地址欄中傳參就行了。

以下兩個方法可能會用到:
1.模型大小自適應

setScaleToFitSize (obj) {
      const boxHelper = new THREE.BoxHelper(obj);
      boxHelper.geometry.computeBoundingBox();
      const box = boxHelper.geometry.boundingBox;
      const maxDiameter = Math.max((box.max.x - box.min.x), (box.max.y - box.min.y), (box.max.z - box.min.z));
      const scaleValue = camera.position.z / maxDiameter;
      obj.position.set(0, -10, 0);//模型擺放的位置
      obj.scale.set(scaleValue, scaleValue, scaleValue);
      scene.add(obj);
    },

2.禁止小程式展示webview時候向下拉動:
mounted中添加:

document.body.addEventListener('touchmove', function (e) {
        e.preventDefault();
      }, { passive: false });

本文轉載於:

https://blog.csdn.net/hzqzzz/article/details/126428029

如果對您有所幫助,歡迎您點個關註,我會定時更新技術文檔,大家一起討論學習,一起進步。

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 首發微信公眾號:SQL資料庫運維 原文鏈接:https://mp.weixin.qq.com/s?__biz=MzI1NTQyNzg3MQ==&mid=2247485212&idx=1&sn=450e9e94fa709b5eeff0de371c62072b&chksm=ea37536cdd40da7 ...
  • 導語 VPN是一種通過公網連接兩個或多個私網站點的專用網路,使得這些站點仿佛是通過專線連接在一起。IPSec是一套協議框架,用於保證數據傳輸的私密性,完整性,真實性。但是VPN網路經常會帶來一些連通性上的問題,通常與MTU設置的不合理有關。本文通過一個實際案例,來具體分析解決這個問題。 作者:陸信宇 ...
  • 作者:vivo 互聯網存儲技術團隊- Qiu Sidi 在企業大數據體系建設過程中,數據採集是其中的首要環節。然而,當前行業內的相關開源數據採集組件,並無法滿足企業大規模數據採集的需求與有效的數據採集治理,所以大部分企業都採用自研開發採集組件的方式。本文通過在vivo的日誌採集服務的設計實踐經驗,為 ...
  • 版權聲明:原創不易,本文禁止抄襲、轉載,侵權必究! 一、DBeaver簡介 DBeaver是一個通用的資料庫管理工具和 SQL 客戶端,社區版的DBeaver只能連接關係型資料庫,比如MySQL、Oracle等,只有企業版以上才能連接非關係型資料庫,比如MongoDB、Redis等;DBeaver ...
  • 原文:Jitpack發佈Android庫出現Direct local .aar file dependencies are not supported when building an AAR - Stars-One的雜貨小窩 問題描述 由於我項目中某個Module引用了本地的aar文件,導致出現了 ...
  • 文章主要闡述了優先順序反轉的一些概念和解決思路,並結合iOS平臺的幾種鎖進行了詳細的調研。通過深入的理解,可以去規避一些不必要的優先順序反轉,從而進一步避免卡死異常。 ...
  • ...
  • 前言 由於工作需要,要抓取tb上某個介面的文案資源,用來分析借鑒。 本來想著,無非就是驗證一下當前用戶信息之類的,但在研究過後,發現並沒那麼簡單。 1,查看請求相關參數 比如下圖,發現請求中攜帶的參數不少,然後其中隨時變化的就有t、sign、data, 很明顯,這就是tb判斷請求是否合法的參數,其中 ...
一周排行
    -Advertisement-
    Play Games
  • 概述:在C#中,++i和i++都是自增運算符,其中++i先增加值再返回,而i++先返回值再增加。應用場景根據需求選擇,首碼適合先增後用,尾碼適合先用後增。詳細示例提供清晰的代碼演示這兩者的操作時機和實際應用。 在C#中,++i 和 i++ 都是自增運算符,但它們在操作上有細微的差異,主要體現在操作的 ...
  • 上次發佈了:Taurus.MVC 性能壓力測試(ap 壓測 和 linux 下wrk 壓測):.NET Core 版本,今天計劃準備壓測一下 .NET 版本,來測試並記錄一下 Taurus.MVC 框架在 .NET 版本的性能,以便後續持續優化改進。 為了方便對比,本文章的電腦環境和測試思路,儘量和... ...
  • .NET WebAPI作為一種構建RESTful服務的強大工具,為開發者提供了便捷的方式來定義、處理HTTP請求並返迴響應。在設計API介面時,正確地接收和解析客戶端發送的數據至關重要。.NET WebAPI提供了一系列特性,如[FromRoute]、[FromQuery]和[FromBody],用 ...
  • 原因:我之所以想做這個項目,是因為在之前查找關於C#/WPF相關資料時,我發現講解圖像濾鏡的資源非常稀缺。此外,我註意到許多現有的開源庫主要基於CPU進行圖像渲染。這種方式在處理大量圖像時,會導致CPU的渲染負擔過重。因此,我將在下文中介紹如何通過GPU渲染來有效實現圖像的各種濾鏡效果。 生成的效果 ...
  • 引言 上一章我們介紹了在xUnit單元測試中用xUnit.DependencyInject來使用依賴註入,上一章我們的Sample.Repository倉儲層有一個批量註入的介面沒有做單元測試,今天用這個示例來演示一下如何用Bogus創建模擬數據 ,和 EFCore 的種子數據生成 Bogus 的優 ...
  • 一、前言 在自己的項目中,涉及到實時心率曲線的繪製,項目上的曲線繪製,一般很難找到能直接用的第三方庫,而且有些還是定製化的功能,所以還是自己繪製比較方便。很多人一聽到自己畫就害怕,感覺很難,今天就分享一個完整的實時心率數據繪製心率曲線圖的例子;之前的博客也分享給DrawingVisual繪製曲線的方 ...
  • 如果你在自定義的 Main 方法中直接使用 App 類並啟動應用程式,但發現 App.xaml 中定義的資源沒有被正確載入,那麼問題可能在於如何正確配置 App.xaml 與你的 App 類的交互。 確保 App.xaml 文件中的 x:Class 屬性正確指向你的 App 類。這樣,當你創建 Ap ...
  • 一:背景 1. 講故事 上個月有個朋友在微信上找到我,說他們的軟體在客戶那邊隔幾天就要崩潰一次,一直都沒有找到原因,讓我幫忙看下怎麼回事,確實工控類的軟體環境複雜難搞,朋友手上有一個崩潰的dump,剛好丟給我來分析一下。 二:WinDbg分析 1. 程式為什麼會崩潰 windbg 有一個厲害之處在於 ...
  • 前言 .NET生態中有許多依賴註入容器。在大多數情況下,微軟提供的內置容器在易用性和性能方面都非常優秀。外加ASP.NET Core預設使用內置容器,使用很方便。 但是筆者在使用中一直有一個頭疼的問題:服務工廠無法提供請求的服務類型相關的信息。這在一般情況下並沒有影響,但是內置容器支持註冊開放泛型服 ...
  • 一、前言 在項目開發過程中,DataGrid是經常使用到的一個數據展示控制項,而通常表格的最後一列是作為操作列存在,比如會有編輯、刪除等功能按鈕。但WPF的原始DataGrid中,預設只支持固定左側列,這跟大家習慣性操作列放最後不符,今天就來介紹一種簡單的方式實現固定右側列。(這裡的實現方式參考的大佬 ...