下载所需要文件,参考:GitHub - yannliao/threejs-example-for-miniprogram: 这是一个 three.js 在微信小程序里的使用示例
引入js文件
import * as THREE from '../../libs/three.weapp.js'import * as TWEEN from '../../libs/tween.umd.js'import { OrbitControls } from '../../jsm/controls/OrbitControls'var isRotate = true //自动旋转var canvas,camera,renderer,controls,scene,new_scene,geometry,texture,material,mesh //3d参数var canvas_2d,ctx_2d //平面画板参数var tagMeshs=[],currentTag=0 //标记参数
初始化3d场景
initThreeD(){let that = thislet picture = this.data.images[this.data.current].thumb_srcwx.createSelectorQuery().select('#c').node().exec((res) => {let canvasId = res[0].node._canvasIdcanvas = THREE.global.registerCanvas(canvasId, res[0].node)this.setData({ canvasId })camera = new THREE.PerspectiveCamera(70, canvas.width / canvas.height, 1, 1000);//camera.position.z = 560;//100camera.position.set(0,500,600)scene = new THREE.Scene();scene.background = new THREE.Color('#F0FFFF');renderer = new THREE.WebGLRenderer({ antialias: true });controls = new OrbitControls(camera, renderer.domElement);controls.autoRotateSpeed = 1.0 controls.enableDamping = true;controls.dampingFactor = 0.25;controls.enableZoom = true;controls.maxZoom = 2.0controls.update();geometry = new THREE.SphereGeometry( 200,30,50);geometry.scale(-1,1,1)texture = new THREE.TextureLoader().load(picture);material = new THREE.MeshBasicMaterial({ map: texture });mesh = new THREE.Mesh(geometry, material);scene.add(mesh);function onWindowResize() {camera.aspect = wx.getSystemInfoSync().screenWidth / wx.getSystemInfoSync().screenHeight;camera.updateProjectionMatrix();renderer.setSize(canvas.width, canvas.height);}function render() {canvas.requestAnimationFrame(render);// mesh.rotation.x += 0.01;controls.autoRotate = isRotateif(isRotate){//mesh.rotation.y += 0.001;//controls.autoRotate = true // 是否自动旋转}controls.update()TWEEN.update()//that.updateTags() //更新标记renderer.render(scene, camera);}render()that.init2d()//初始化2d-canvas画板//初始动画setTimeout(function(){that.startAnimation()},1000)//监听窗口变化wx.onWindowResize((result) => {onWindowResize()})})}
初始化光源
nitLight() {let ambientLight;let directionalLight;ambientLight = new THREE.AmbientLight(0xffffff);scene.add(ambientLight);directionalLight = new THREE.DirectionalLight(0xffffff, 0.2);directionalLight.position.set(-50, 50, 10);directionalLight.castShadow = true;directionalLight.shadow.mapSize.width = 1024;directionalLight.shadow.mapSize.height = 1024;// 为光线设置阴影属性directionalLight.shadow.camera.left = -50;directionalLight.shadow.camera.right = 50;directionalLight.shadow.camera.top = 50;directionalLight.shadow.camera.bottom = -50;directionalLight.shadow.camera.far = 3500;// 偏差率directionalLight.shadow.bias = -0.001;scene.add(directionalLight);// let directionalLightHelper = new THREE.DirectionalLightHelper(directionalLight, 10);// scene.add(directionalLightHelper);}