👨⚕️ 主页: gis分享者
👨⚕️ 感谢各位大佬 点赞👍 收藏⭐ 留言📝 加关注✅!
👨⚕️ 收录于专栏:threejs gis工程师
文章目录
- 一、🍀前言
- 1.1 ☘️WebWorker web端多线程
- 二、🍀实现配合使用WebWorker
- 1. ☘️实现思路
- 2. ☘️代码样例
一、🍀前言
本文详细介绍如何基于threejs在三维场景中实现配合使用WebWorker,亲测可用。希望能帮助到您。一起学习,加油!加油!
1.1 ☘️WebWorker web端多线程
WebWorker 是运行在浏览器后台的一个单独的线程,因此可以执行一些耗时的操作而不会阻塞主线程。WebWorker 通过与主线程之间传递消息实现通信,这种通信是双向的。WebWorker不能直接访问 DOM,也不能使用像 window 对象这样的浏览器接口对象,但可以使用一些WebWorker 标准接口和 Navigator 对象的部分属性和方法。
应用场景:
数据分析:Web Worker可以用于处理图像处理、数据挖掘、神经网络等耗时任务,这些任务通常需要大量的计算资源,使用Web Worker可以在不阻塞用户界面的情况下进行。
大量计算:适用于科学计算、物理模拟等需要大量计算的任务。通过在后台运行,Web Worker可以显著提高应用的性能和响应速度。
网络数据传输:例如文件上传/下载、消息推送等任务可以通过Web Worker在后台执行,不会影响页面的交互。
实时数据更新:Web Worker可以定时获取数据并在后台处理和更新,保持网页内容的实时性。
游戏开发:在游戏开发中,Web Worker可以用于处理游戏逻辑、碰撞检测和物理模拟等任务,提高游戏的性能和流畅度。
二、🍀实现配合使用WebWorker
1. ☘️实现思路
- 1、初始化renderer渲染器
- 2、初始化Scene三维场景
- 3、初始化camera相机,定义相机位置 camera.position.set,设置相机方向camera.lookAt。
- 4、初始化THREE.AmbientLight环境光源,scene场景加入环境光源,初始化THREE.PointLight平行光源,设置平行光源位置,设置平行光源投影,scene添加平行光源。
- 5、加载几何模型:创建THREE.PlaneGeometry平面几何体planeGeometry。创建THREE.MeshLambertMaterial漫反射材质planeMaterial。传入参数planeGeometry和planeMaterial创建网格对象plane,设置旋转角度和投影,scene场景加入plane。生成随机1000个小方块模型组group,cene场景加入group(具体代码参考下面代码样例)。创建WebWorker多线程对象myWorker。 创建THREE.GLTFLoader gltf模型加载器loader,调用loader的load方法,加载‘scene.gltf’动漫模型,在回调函数中,scene场景加入该动漫模型gltf.scene,播放模型动画,同myWorker线程进行通信,实时改变group中小方块的位置信息。
- 6、加入controls、gui控制,加入stats监控器,监控帧数信息。
2. ☘️代码样例
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>learn63(实现配合使用WEB WORKERS)</title><script src="lib/threejs/127/three.js-master/build/three.js"></script><script src="lib/threejs/127/three.js-master/examples/js/controls/OrbitControls.js"></script><script src="lib/threejs/127/three.js-master/examples/js/libs/stats.min.js"></script><script src="lib/threejs/127/three.js-master/examples/js/libs/dat.gui.min.js"></script><script src="lib/threejs/127/three.js-master/examples/js/loaders/GLTFLoader.js"></script><script src="lib/js/Detector.js"></script>
</head>
<style type="text/css">html, body {margin: 0;height: 100%;}canvas {display: block;}</style>
<body onload="draw()">
</body>
<script>// web Workers线程内是无法获取到window对象var renderer, camera, scene, gui, stats, ambientLight, directionalLight, controlsvar mixer, clock = new THREE.Clock()var initRender = () => {renderer = new THREE.WebGLRenderer({antialias: true})renderer.setSize(window.innerWidth, window.innerHeight)renderer.shadowMap.enabled = truedocument.body.appendChild(renderer.domElement)}var initCamera = () => {camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000)camera.position.set(0, 30, 60)camera.lookAt(new THREE.Vector3(0, 0, 0))}var initScene = () => {scene = new THREE.Scene()}var initLight = () => {ambientLight = new THREE.AmbientLight('#bbbbbb')scene.add(ambientLight)directionalLight = new THREE.DirectionalLight('#ffffff')directionalLight.position.set(40, 60, 10)directionalLight.shadow.camera.near = 1; //产生阴影的最近距离directionalLight.shadow.camera.far = 400; //产生阴影的最远距离directionalLight.shadow.camera.left = -50; //产生阴影距离位置的最左边位置directionalLight.shadow.camera.right = 50; //最右边directionalLight.shadow.camera.top = 50; //最上边directionalLight.shadow.camera.bottom = -50; //最下面//这两个值决定生成阴影密度 默认512directionalLight.shadow.mapSize.height = 1024;directionalLight.shadow.mapSize.width = 1024;directionalLight.castShadow = truescene.add(directionalLight)}var initModel = () => {var planeGeometry = new THREE.PlaneGeometry(1000, 1000)var planeMaterial = new THREE.MeshLambertMaterial({color: 0x333333, side: THREE.DoubleSide})var plane = new THREE.Mesh(planeGeometry, planeMaterial)plane.rotation.x = -0.5 * Math.PI// plane.position.y = -.1plane.receiveShadow = truescene.add(plane)// 生成随机小正方体function randomCube() {let material = new THREE.MeshBasicMaterial({color: 0xffffff * Math.random()})let boxSize = Math.random() * 0.5let geometry = new THREE.BoxGeometry(boxSize, boxSize, boxSize)let mesh = new THREE.Mesh(geometry, material)mesh.position.set(Math.random() * 100 - 50, -3, Math.random() * 100 - 50)mesh.speed = Math.random()return mesh}let group = new THREE.Group()let arr = []for (let i = 0; i < 1000; i++) {group.add(randomCube())arr.push({speed: Math.random(),y: -3})}scene.add(group)//创建webWorkersif (!window.Worker) {alert("你的电脑不支持web Workers")}let myWorker = new Worker('lib/js/worker.js')var loader = new THREE.GLTFLoader()loader.load('data/model/dongman/scene.gltf', gltf => {gltf.scene.scale.set(.1, .1, .1)gltf.scene.traverse(child => {if (child.isMesh) {child.castShadow = true// child.receiveShadow = true// 视锥体剔除child.frustumCulled = false}})scene.add(gltf.scene)var obj = gltf.scenemeshHelper = new THREE.SkeletonHelper(obj)// scene.add(meshHelper)mixer = new THREE.AnimationMixer(obj)action = mixer.clipAction(gltf.animations[0])action.play()//在模型加载完成后,链接worker线程myWorker.postMessage(arr)myWorker.onmessage = function (e) {for (let i = 0; i < e.data.length; i++) {group.children[i].position.y = e.data[i].y}}})}var initStats = () => {stats = new Stats()document.body.appendChild(stats.dom)}var initControls = () => {controls = new THREE.OrbitControls(camera, renderer.domElement)controls.target.set(0, 15, 0)controls.enableDamping = true}var render = () => {controls.update()var time = clock.getDelta()if (mixer) {mixer.update(time)}renderer.render(scene, camera)}var onWindowResize = () => {camera.aspect = window.innerWidth / window.innerHeightcamera.updateProjectionMatrix()renderer.setSize(window.innerWidth, window.innerHeight)}var animate = () => {render()stats.update()requestAnimationFrame(animate)}var draw = () => {initRender()initScene()initCamera()initLight()initModel()initStats()initControls()animate()window.onresize = onWindowResize}
</script>
</html>
worker.js 代码示例:
onmessage = function (e) {let arr = e.data;//设置定时器setInterval(function () {for (let i = 0; i < arr.length; i++) {arr[i].y += arr[i].speed;if (arr[i].y >= 80) {arr[i].y = -3;}}postMessage(arr);}, 1000 / 60);
};
效果如下: