当前位置:   article > 正文

three.js实现VR看房自由_js 实现vr看房功能

js 实现vr看房功能

需求:

       在很多看房软件,例如贝壳看房、VR展馆或者VR展厅等等,为了更加真实的展示产品或者场景的特色,通常会通过一些VR或者全景图的方式,给用户带来沉浸式的体验,给视觉上带来比较震撼的效果,再加上一些动感的音乐,仿佛让人深陷其中,无法自拔。假的,因为这些实现效果比较便宜,而且性能要求不高

实现原理:

      通过全景图的方式实现,其实就是在一个球体内部或者球体双面贴上全景图(下面简称全景球),让相机位于该球体的中心,当鼠标移动是,旋转相机即可;当需要漫游的时候,根据点击的点位获取下一个相机位置,并将相机移动至点击的全景球,影藏其他的全景球,显示下一个全景球;重复上面过程。怎么样,是不是很简单?

需要解决哪些问题:

1.初始化场景的时候相机是出于什么位置或者姿态?

答:从众多点位中的选取一个全景球的中心位置相机高度可以根据需要调节,作为相机的初始位置,不然相机就跑去了全景球导致看的脏东西。

2.当点击地面上的轨迹时,如何找到下一个全景球,也就是即将要进入的全景球

答:因为轨迹的点位和全景球在创建的时候,是有规律的,比如他们的命名是一一对应的,例如全景球的命名为VR_AA,那全景球对应的轨迹点可以命名为VR_A;当我们点击的到轨迹点VR_A时,就可以根据字符串的包含在之前的全景球数组中找到VR_AA,并且将它显示出来,这种情况每次都要遍历一次全景球数组;当然也可以创建一个方法,根据传进去的轨迹点name,然后对于的全景球

3.相机如何平滑的移动到指定的位置?

答:我们可以利用一个叫tweenjs/tween.js的库,把相机当前位置和目标位置生成一个平滑的过渡效果,然后应用在相机上就可以了

4.如果单纯的现实目标全景球和影藏全景球,那效果太生硬了,和网上看到的VR效果差别很大,如何实现显示和影藏的效果渐变呢?

答:相机在当前全景球位置平滑移动至目标全景球时,会有一个距离的比率ratio,这个比率很好理解,从A移动到B的时候,如果还没开始那ratio就是1.0;如果朝着B移动的距离是一半,那就是0.5;如果到达B了,那ratio就是0.0了,而这个ratio就可以用来设置A的透明度;而B的透明度则是1.0-ratio。

标签:坐标精准度不高

      试想一下,在任何三维场景或者VR的场景中我们都会有很多标签信息,并绑定一些事件进行交互,然而这些标签的位置基本都是手动在场景中进行拾取的,那会带来什么问题呢?因为我们位于全景图中,当点击全景图中的物体的时候(其实点击的就是全景图中的某个位置),比如我们在全景球A中标记了空调的位置,并且保存了位置。那么这个空调的位置只会在全景球A中生效,也就是可以正确的展示空调的位置上,在其他的全景球无法正确展示空调的位置

       解决办法一:把标签打在模型上面,也就是在全景球外面加载一个简单的模型作为辅助,不过不展示它,鼠标拾取位置的时候,拾取鼠标模型上的点作为标签的位置;这样子可以稍微解决一下标签位置不准确的位置上,但是也会有一定的误差,但是整个VR场景只需要一套标签即可

      解决办法二:那就是简单粗暴,每个全景球对于一套标签,这样子位置绝对的准确,但是显得有点笨拙。

控制器:自定义一个VR控制器

因为three.js没有自带的类似babylon.js中的Freecamera, 可以根据官方的demo写一个简单版的控制器,控制器可以鼠标移动的来决定的相机的旋转,以下是控制代码

  1. import * as THREE from "three";
  2. export default class VRcontrol extends THREE.EventDispatcher {
  3. autoRotate = false;
  4. onPointerDownMouseX = 0;
  5. onPointerDownMouseY = 0;
  6. lon = 0;
  7. onPointerDownLon = 0;
  8. lat = 0;
  9. onPointerDownLat = 0;
  10. phi = 0;
  11. theta = 0;
  12. keyDown = false;
  13. camera: THREE.PerspectiveCamera;
  14. domElement: HTMLElement;
  15. constructor(camera: THREE.PerspectiveCamera, domElement: HTMLElement) {
  16. super();
  17. this.camera = camera;
  18. this.domElement = domElement;
  19. this.domElement.addEventListener(
  20. "pointerdown",
  21. this.onPointerDown.bind(this)
  22. );
  23. this.domElement.addEventListener(
  24. "pointermove",
  25. this.onPointerMove.bind(this)
  26. );
  27. window.addEventListener("pointerup", this.onPointerUp.bind(this));
  28. this.domElement.addEventListener(
  29. "wheel",
  30. this.onDocumentMouseWheel.bind(this)
  31. );
  32. }
  33. onPointerDown(event: PointerEvent) {
  34. if (event.isPrimary === false) return;
  35. this.keyDown = true;
  36. this.onPointerDownMouseX = event.clientX;
  37. this.onPointerDownMouseY = event.clientY;
  38. this.onPointerDownLon = this.lon;
  39. this.onPointerDownLat = this.lat;
  40. }
  41. onPointerMove(event: PointerEvent) {
  42. if (event.isPrimary === false || !this.keyDown) return;
  43. this.lon =
  44. (this.onPointerDownMouseX - event.clientX) * 0.1 + this.onPointerDownLon;
  45. this.lat =
  46. (event.clientY - this.onPointerDownMouseY) * 0.1 + this.onPointerDownLat;
  47. // 分发事件
  48. this.dispatchEvent({
  49. type: "camera",
  50. camera: this.camera,
  51. });
  52. }
  53. onPointerUp(event: PointerEvent) {
  54. if (event.isPrimary === false) return;
  55. this.keyDown = false;
  56. this.domElement.removeEventListener("pointermove", this.onPointerMove);
  57. }
  58. onDocumentMouseWheel(event: WheelEvent) {
  59. const fov = this.camera.fov + event.deltaY * 0.05;
  60. this.camera.fov = THREE.MathUtils.clamp(fov, 10, 75);
  61. this.camera.updateProjectionMatrix();
  62. }
  63. update() {
  64. if (this.autoRotate) {
  65. this.lon += 0.1;
  66. }
  67. this.lat = Math.max(-85, Math.min(85, this.lat));
  68. this.phi = THREE.MathUtils.degToRad(90 - this.lat);
  69. this.theta = THREE.MathUtils.degToRad(this.lon);
  70. const x = 500 * Math.sin(this.phi) * Math.cos(this.theta);
  71. const y = 500 * Math.cos(this.phi);
  72. const z = 500 * Math.sin(this.phi) * Math.sin(this.theta);
  73. this.camera.lookAt(x, y, z);
  74. }
  75. remove() {
  76. this.domElement.removeEventListener(
  77. "pointerdown",
  78. this.onPointerDown.bind(this)
  79. );
  80. this.domElement.removeEventListener(
  81. "pointermove",
  82. this.onPointerMove.bind(this)
  83. );
  84. window.removeEventListener("pointerup", this.onPointerUp.bind(this));
  85. this.domElement.removeEventListener(
  86. "wheel",
  87. this.onDocumentMouseWheel.bind(this)
  88. );
  89. }
  90. }

接下来给出场景的核心代码,里面写的是一些demo,没有经过封装,里面包含了两个渲染器,一个是webGL,另外一个是CSS2DRenderer,主要用来渲染标签,里面也包含了一些创建标签的方法

  1. import * as THREE from "three";
  2. import FirstPersonCameraControl from "../controls/Mycontrol";
  3. import { CSS2DRenderer } from "three/examples/jsm/renderers/CSS2DRenderer";
  4. import {
  5. createrPoint,
  6. createVRItem,
  7. createVideoLabel,
  8. createIconLabel,
  9. } from "../tools";
  10. import TWEEN from "@tweenjs/tween.js";
  11. export default class VR extends THREE.EventDispatcher {
  12. radii: number;
  13. parent: THREE.Group;
  14. pointObj: THREE.Group;
  15. currentVRItem: THREE.Mesh | any;
  16. preVRItem: THREE.Mesh | any;
  17. container: string | HTMLElement | any;
  18. scene: THREE.Scene;
  19. camera: THREE.PerspectiveCamera;
  20. renderer: THREE.WebGLRenderer;
  21. labelRenderer: CSS2DRenderer;
  22. initLocaltion: any;
  23. raycaster: THREE.Raycaster;
  24. mouse: THREE.Vector2;
  25. control: any;
  26. getMousePosition: (event: any) => void;
  27. onMouseDown: (event: any) => void;
  28. onResize: () => void;
  29. marking: boolean;
  30. labelContent: string;
  31. videoUrl: string;
  32. imgUrl: string;
  33. labelType: number;
  34. effective: number;
  35. textures: THREE.Texture[] = [];
  36. clock = new THREE.Clock();
  37. Pupop: THREE.Object3D<THREE.Event> | undefined;
  38. constructor(option: any) {
  39. super();
  40. this.marking = false;
  41. this.videoUrl = "";
  42. this.labelContent = "";
  43. this.imgUrl = "";
  44. this.labelType = 0;
  45. this.effective = 1;
  46. this.radii = 4; // 全景球半径
  47. this.pointObj = new THREE.Group();
  48. this.parent = new THREE.Group();
  49. this.container =
  50. option.container instanceof HTMLElement
  51. ? option.container
  52. : document.getElementById(option.container); // 渲染的DOM节点
  53. this.scene = new THREE.Scene(); // 三维场景
  54. this.scene.background = new THREE.Color(0xaaccff);
  55. this.scene.add(this.parent); // 全景球集合
  56. this.scene.add(this.pointObj); // 点集合
  57. this.camera = new THREE.PerspectiveCamera(
  58. 70,
  59. this.container.clientWidth / this.container.clientHeight,
  60. 0.05,
  61. 500
  62. ); // 透视相机初始化
  63. // 初始化渲染器
  64. this.renderer = new THREE.WebGLRenderer({
  65. antialias: true,
  66. alpha: true,
  67. logarithmicDepthBuffer: true,
  68. });
  69. // 初始化标签渲染器
  70. this.labelRenderer = new CSS2DRenderer();
  71. this.labelRenderer.setSize(
  72. this.container.clientWidth,
  73. this.container.clientHeight
  74. );
  75. this.labelRenderer.domElement.style.position = "absolute";
  76. this.labelRenderer.domElement.style.top = "0px";
  77. this.renderer.setSize(
  78. this.container.clientWidth,
  79. this.container.clientHeight
  80. );
  81. // 设置渲染的尺寸
  82. // this.renderer.setPixelRatio = window.devicePixelRatio
  83. this.renderer.setClearColor(new THREE.Color("#1e1e1e"));
  84. this.initLocaltion = option.initLocaltion; // 全景图初始位置
  85. this.container.appendChild(this.labelRenderer.domElement);
  86. this.container.appendChild(this.renderer.domElement);
  87. this.raycaster = new THREE.Raycaster(); // 初始化射线
  88. this.mouse = new THREE.Vector2(); //初始化鼠标位置
  89. // 控制器
  90. this.control = new FirstPersonCameraControl(
  91. this.camera,
  92. this.labelRenderer.domElement
  93. );
  94. // 获取鼠标坐标
  95. this.getMousePosition = function (event) {
  96. this.mouse.x = (event.offsetX / this.container.clientWidth) * 2 - 1;
  97. this.mouse.y = -(event.offsetY / this.container.clientHeight) * 2 + 1; //这里为什么是-号,没有就无法点中
  98. };
  99. this.onMouseDown = async function (event) {
  100. this.getMousePosition(event);
  101. //将平面坐标系转为世界坐标系
  102. this.raycaster.setFromCamera(this.mouse, this.camera);
  103. //得到点击的几何体
  104. const raycasters = this.raycaster.intersectObjects(
  105. this.pointObj.children
  106. );
  107. const name = raycasters.length > 0 && raycasters[0].object.name;
  108. this.currentVRItem = this.scene.getObjectByName(name + "VR");
  109. if (this.currentVRItem) {
  110. const position = this.currentVRItem.position.clone();
  111. this.ChangeScene(position, () => {
  112. this.parent.children.forEach((mesh) => {
  113. if (mesh.name != name + "VR") {
  114. mesh.visible = false;
  115. }
  116. });
  117. });
  118. }
  119. const currentVRLocal = raycasters.find((item) => {
  120. if (item.distance > this.radii - 0.2 && item.distance < this.radii) {
  121. return item;
  122. }
  123. });
  124. let currentLabel;
  125. if (currentVRLocal && this.marking) {
  126. switch (this.labelType) {
  127. case 0:
  128. const position = currentVRLocal.point.clone();
  129. case 1:
  130. currentLabel = this.imgUrl && createIconLabel(this.imgUrl);
  131. break;
  132. case 2:
  133. currentLabel = this.videoUrl && createVideoLabel(this.videoUrl);
  134. default:
  135. break;
  136. }
  137. const position = currentVRLocal.point.clone();
  138. currentLabel && currentLabel.position.copy(position);
  139. currentLabel && this.scene.add(currentLabel);
  140. }
  141. };
  142. this.onResize = function () {
  143. this.renderer.setSize(
  144. this.container.clientWidth,
  145. this.container.clientHeight
  146. );
  147. this.camera.aspect =
  148. this.container.clientWidth / this.container.clientHeight;
  149. this.camera.updateProjectionMatrix();
  150. };
  151. this.container.addEventListener(
  152. "mousedown",
  153. this.onMouseDown.bind(this),
  154. false
  155. ); // 鼠标点击事件
  156. window.addEventListener("resize", this.onResize.bind(this), false); // 窗口缩重新渲染
  157. }
  158. // 切换动画
  159. ChangeScene(newTarget: THREE.Vector3, callback: () => void) {
  160. const leng = this.camera.position.clone().distanceTo(newTarget);
  161. const time = THREE.MathUtils.clamp(leng * 200, 800, 1200);
  162. const that = this;
  163. that.currentVRItem.visible = true;
  164. new TWEEN.Tween(that.camera.position)
  165. .to(newTarget, time)
  166. // easing缓动函数,Out表示最开始加速,最后放缓
  167. .easing(TWEEN.Easing.Quadratic.InOut)
  168. .onUpdate(function () {
  169. const ratio = that.camera.position.distanceTo(newTarget);
  170. const Ratio = ratio / leng;
  171. if (that.currentVRItem) {
  172. that.currentVRItem.material.uniforms.ratio.value = 1 - Ratio;
  173. }
  174. that.dispatchEvent({
  175. type: "camera",
  176. camera: that.camera,
  177. });
  178. })
  179. .start()
  180. .onComplete(function () {
  181. that.preVRItem = that.currentVRItem;
  182. callback();
  183. });
  184. }
  185. // 渲染函数
  186. renderFn() {
  187. TWEEN.update();
  188. this.control.update();
  189. this.renderer.render(this.scene, this.camera);
  190. this.labelRenderer.render(this.scene, this.camera);
  191. requestAnimationFrame(this.renderFn.bind(this));
  192. }
  193. initVR(infoList: any[]) {
  194. infoList.forEach((item) => {
  195. const point = createrPoint(item.id, item.tz, -0.5 * this.radii, item.tx);
  196. this.pointObj.add(point);
  197. const VRitem = createVRItem(
  198. item.img,
  199. item.id + "VR",
  200. item.tz,
  201. item.ty,
  202. item.tx
  203. );
  204. this.parent.add(VRitem.skyBox);
  205. this.textures.push(VRitem.textureA);
  206. });
  207. if (this.initLocaltion) {
  208. this.preVRItem = this.scene.getObjectByName(this.initLocaltion);
  209. } else {
  210. this.preVRItem = this.parent.children[0];
  211. }
  212. this.preVRItem.visible = true;
  213. this.camera.position.set(
  214. this.preVRItem.position.x,
  215. this.preVRItem.position.y,
  216. this.preVRItem.position.z
  217. );
  218. }
  219. dispose() {
  220. this.scene.children.forEach((item) => {
  221. if (item instanceof THREE.Mesh) {
  222. item.material.dispose();
  223. item.geometry.dispose();
  224. }
  225. });
  226. this.textures.forEach((texture) => {
  227. texture.dispose();
  228. });
  229. this.renderer.clear()
  230. this.renderer.forceContextLoss();
  231. this.renderer.dispose();
  232. this.scene.clear();
  233. }
  234. }

还有一下几个工具方法,用来创建轨迹点的createrPoint,创建全景球的createVRItem,在着色器材质中,接收一个从当前点到下一个点的距离除以总距离,得到一个比率ratio,将这个比率作为一个透明度,传给着色器

  1. import * as THREE from "three";
  2. import { CSS2DObject } from "three/examples/jsm/renderers/CSS2DRenderer";
  3. import { Font, FontLoader } from "three/examples/jsm/loaders/FontLoader";
  4. import { TextGeometry } from "three/examples/jsm/geometries/TextGeometry";
  5. /**
  6. *
  7. * @param {string} id
  8. * @param {string} tx
  9. * @param {string} ty
  10. * @param {string} tz
  11. * @returns {THREE.Mesh}
  12. */
  13. export const createrPoint = (
  14. id: string,
  15. tx: number,
  16. ty: number,
  17. tz = 0
  18. ): THREE.Mesh => {
  19. const geometry = new THREE.CircleGeometry(0.15, 30);
  20. const material = new THREE.MeshBasicMaterial({ color: "#eeeeee" });
  21. const circle = new THREE.Mesh(geometry, material);
  22. circle.name = id;
  23. circle.translateX(tx);
  24. circle.translateY(ty);
  25. circle.translateZ(tz);
  26. circle.rotateX(-Math.PI / 2);
  27. return circle;
  28. };
  29. export const createVRItem = (
  30. url: string,
  31. id: string,
  32. tx: number,
  33. ty: number,
  34. tz = 0,
  35. radii = 4
  36. ) => {
  37. const vertexShader = `
  38. varying vec2 vUv;
  39. void main(){
  40. vUv = uv;
  41. gl_Position = projectionMatrix*viewMatrix*modelMatrix*vec4( position, 1.0 );
  42. }
  43. `;
  44. const fragmentShader = `
  45. uniform sampler2D texture1;
  46. uniform float ratio;
  47. varying vec2 vUv;
  48. void main() {
  49. vec4 vcolor = texture2D( texture1, vUv );
  50. vec4 tcolor = vec4(0.,0.,0.,0.);
  51. gl_FragColor = mix(tcolor,vcolor,ratio);
  52. }
  53. `;
  54. const textureA = new THREE.TextureLoader().load(url);
  55. const materialObj = new THREE.ShaderMaterial({
  56. uniforms: {
  57. texture1: {
  58. value: textureA,
  59. },
  60. ratio: {
  61. value: 1.0,
  62. },
  63. },
  64. vertexShader,
  65. fragmentShader,
  66. });
  67. materialObj.transparent = true;
  68. materialObj.depthWrite = false;
  69. const skyBox = new THREE.Mesh(
  70. new THREE.SphereGeometry(radii, 40, 40),
  71. materialObj
  72. );
  73. skyBox.name = id;
  74. skyBox.translateX(tx);
  75. skyBox.translateY(0);
  76. skyBox.translateZ(tz);
  77. skyBox.geometry.scale(1, 1, -1);
  78. skyBox.visible = false;
  79. return {
  80. skyBox,
  81. textureA,
  82. };
  83. };
  84. export const createVideoLabel = (url: string): CSS2DObject => {
  85. const x = document.createElement("video");
  86. x.setAttribute("width", "320");
  87. x.setAttribute("height", "240");
  88. x.setAttribute("controls", "controls");
  89. x.setAttribute("src", url);
  90. const videoObj = new CSS2DObject(x);
  91. videoObj.name = "video";
  92. return videoObj;
  93. };
  94. export const createIconLabel = (url: string, height = 50): CSS2DObject => {
  95. const img = document.createElement("img");
  96. img.src = url;
  97. img.height = height;
  98. const imgObj = new CSS2DObject(img);
  99. imgObj.name = "icon";
  100. return imgObj;
  101. };
  102. export const text3D = async (text: string): Promise<THREE.Mesh> => {
  103. const loader = new FontLoader();
  104. return new Promise((resolve) => {
  105. loader.load("font/helvetiker_regular.typeface.json", function (response) {
  106. const textGeo = new TextGeometry(text, {
  107. font: response,
  108. size: 1,
  109. height: 200,
  110. curveSegments: 1,
  111. bevelThickness: 1,
  112. bevelSize: 1,
  113. bevelEnabled: false,
  114. });
  115. const materials = [
  116. new THREE.MeshPhongMaterial({ color: 0xffffff, flatShading: true }), // front
  117. new THREE.MeshPhongMaterial({ color: 0xffffff }), // side
  118. ];
  119. const mesh = new THREE.Mesh(textGeo, materials);
  120. resolve(mesh);
  121. });
  122. });
  123. };

使用的时候直接实例化VR这个类就可以了

  1. vrScene = new VR({
  2. container: 'threeContainer'
  3. })
  4. vrScene.initVR(dataList)
  5. vrScene.renderFn()
  6. vrScene.addEventListener('camera', cameraFn)
  7. }
  8. })
  1. export const dataList = [
  2. {
  3. id: '01',
  4. tx: 0,
  5. ty: 0,
  6. tz: 0,
  7. img: 'models/gardent/别墅_地下室.jpg'
  8. },
  9. {
  10. id: '02',
  11. tx: 2,
  12. ty: 0,
  13. tz: 2,
  14. img: 'models/gardent/别墅_主卫.jpg'
  15. },
  16. {
  17. id: '03',
  18. tx: 2,
  19. ty: 0,
  20. tz: 5,
  21. img: 'models/gardent/别墅_主卧.jpg'
  22. },
  23. {
  24. id: '04',
  25. tx: 5,
  26. ty: 0,
  27. tz: 9,
  28. img: 'models/gardent/卧室1.jpg'
  29. },
  30. {
  31. id: '05',
  32. tx: 6,
  33. ty: 0,
  34. tz: 1,
  35. img: 'models/gardent/卧室2.jpg'
  36. }
  37. ]

上面是数据格式

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/871143
推荐阅读
相关标签
  

闽ICP备14008679号