微信小程序實現從外部加載3d模型
1.3d模型的幾種格式?
2.怎樣加載3d模型?
3.總結(貼了自己寫的整個項目github地址)
1.模型的格式
小程序支持從外部加載3d模型的幾種格式有:
a.obj格式
b.gltf格式
c.fbx格式
就列舉這幾種
2.加載3d模型
用 gltf 格式的模型
gltf 3d模式格式有兩種:
gltf是一個基於json的文本文件,如紋理貼圖和二進制網格數據;
glb是二進制版本,通常較小且獨立,但不易編輯。
(1)首先文件
下載 three.js github地址
(2)導入文件
需要導入three.js 和 gltf-loader.js (加載模型)
從下載好的壓縮包裏複製目錄 threejs-miniprogram-master\example\miniprogram_npm\threejs-miniprogram 的 [index.js] 文件
以及 threejs-miniprogram-master\example\loaders 裏的 [gltf-loader.js] 文件
(3)寫代碼
① index.wxml
<view style="height: 50px"></view>
<canvas type="webgl" id="webgl" style="width: 100%; height: 450px;"></canvas>
<canvas type="webgl" id="webgl" style="width: 100%; height: 300px;"></canvas>
② inde.js
重點:導入兩個文件夾,裏面分別有文件 three.js 和 gltf-loader.js(導入外部模型)
需要設置場景裏的相機 、光線以及渲染器
import { createScopedThreejs } from 'threejs-miniprogram';
import { registerGLTFLoader } from '../loaders/gltf-loader';
const app = getApp();
var camera, scene, renderer, model;
var requestAnimationFrame; // 動畫回調函數
Page({
data: {},
onLoad: function () {
let that = this;
var query = wx.createSelectorQuery();
query.select('#webgl').node().exec((res) => {
var canvas = res[0].node;
// 設置背景透明
var gl = canvas.getContext('webgl', {
alpha: true
});
if (canvas != undefined) {
// canvas.width 和canvas.style都需要設置,否則無法顯示渲染
canvas.width = canvas._width;
canvas.height = canvas._height;
requestAnimationFrame = canvas.requestAnimationFrame;
that.init(canvas);
}
});
},
init: function(canvas){
let that = this;
const THREE = createScopedThreejs(canvas)
registerGLTFLoader(THREE)
//設置相機
camera = new THREE.PerspectiveCamera(45, canvas.width / canvas.height, 0.25, 100);
camera.position.set(- 5, 3, 10);
camera.lookAt(new THREE.Vector3(0, 2, 0));
scene = new THREE.Scene();
//設置光線
var light = new THREE.HemisphereLight(0xffffff, 0x444444);
light.position.set(0, 20, 0);
scene.add(light);
light = new THREE.DirectionalLight(0xffffff);
light.position.set(0, 20, 10);
scene.add(light);
//加載外部模型
var loader = new THREE.GLTFLoader();
loader.load('https://threejs.org/examples/models/gltf/RobotExpressive/RobotExpressive.glb', function (gltf) {
model = gltf.scene;
scene.add(model);
}, undefined, function (e) {
console.error(e);
});
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(canvas.width, canvas.height);
//調用動畫
that.animate();
},
animate:function(){
let that = this;
requestAnimationFrame(that.animate);
renderer.render(scene, camera);
}
})
3.總結
整個實現過程,下載three.js 和 gltf-loader.js ,兩個文件放自己項目裏,在代碼中設置好場景參數,導入模型即可。
整個項目代碼:github地址
csdn地址(推薦去github上下載,因爲我在上傳到csdn時,設置要積分才能下載 ^ _ ^)
小白一個,歡迎指出問題 ~~