How can we set the frame rate of the page if we want to see it in the process of using threejs? Threejs provides us with a frame rate detection method, which is also relatively simple to use. The effect is as shown in the figure below. The frame rate detection window is displayed in the upper left corner of the page window.
It only takes three steps to use such a function:
import Stat from 'three/examples/jsm/libs/stats.module' //引入帧率检测 const stat = new Stat() //定义帧率检测 stat.update() //在动画中更新帧率检测
When using the above three steps, you need to have a written animation. You can only insert these three steps into the corresponding places. The following is a use case. Enter in the main.js file
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() //在动画中更新帧率检测 }