在使用threejs的过程中如果我们想看页面的帧率应该怎么设置出来呢?threejs为我们提供帧率检测方法,使用起来也比较简单。效果如下图,在页面窗口的左上角显示这样的帧率检测窗口。

想要使用这样的功能只需3步即可:
import Stat from 'three/examples/jsm/libs/stats.module' //引入帧率检测 const stat = new Stat() //定义帧率检测 stat.update() //在动画中更新帧率检测
在使用以上3步的时候需要有写好的动画,将这3步分别插入相应地方才可以,下面是使用案例。在main.js文件中输入
import * as THREE from 'three' import Stat from 'three/examples/jsm/libs/stats.module' //引入帧率检测 const w =window.innerWidth const h =window.innerHeight const stat = new Stat() //定义帧率检测 //Scene(场景) const scene=new THREE.Scene() //坐标轴 const axes = new THREE.AxesHelper(2,2,2) scene.add(axes) let cubes=[] //创建一个立方体,物体:geometry(几何体,骨架) + material(材质,皮肤) function createCube(){ let d = Math.random() const geometry = new THREE.BoxGeometry(d,d,d) //生成长宽高随机的立方体 const material = new THREE.MeshBasicMaterial({color:0xffff00*Math.random()}) //给材质添加颜色,可以使用css的颜色,但是需要引号:{color:'#666'} const cube=new THREE.Mesh(geometry,material) cube.position.x=(Math.random()-0.5)*4 cube.position.y=(Math.random()-0.5)*4 cube.position.z=(Math.random()-0.5)*4 cubes.push(cube) } //循环生成立方体 let n=20 for(let i = 0;i{ scene.add(cube) }) //创建光线 const light = new THREE.AmbientLight() //把光线放入场景 scene.add(light) //创建一个相机 const camera=new THREE.PerspectiveCamera(75,w/h,0.1,100) //75是能看到的角度范围 camera.position.set(0,0,5) camera.lookAt(0,0,0) //创建渲染器 const renderer=new THREE.WebGLRenderer() renderer.setSize(w,h) document.body.append(renderer.domElement) document.body.append(stat.domElement) //动画 const clock=new THREE.Clock() tick() function tick(){ const time=clock.getElapsedTime() cubes.forEach((cube,index)=>{ cube.rotation.x=Math.sin(time*2)*2+index cube.rotation.y=Math.cos(time*2)*2+index }) requestAnimationFrame(tick) renderer.render(scene,camera) stat.update() //在动画中更新帧率检测 }