记录学习Three.js过程(二)

167 阅读1分钟

前言

记录Gsap的基本使用,以及实现自适应画面、进入与退出全屏

  1. GSAP的相关使用
// 设置动画,相关参数,利用变量接受动画的实例
let animate = gsap.to(cube.position, {
   x: 5,
   duration: 5,
   // 设置动画效果
   ease: 'power1.inOut',
   // 设置重复的次数,无限次循环-1
   repeat: 1,
   // 是否往返运动
   yoyo: true,
   // 延迟运动,延迟多少秒才开始运动
   // delay: 2,
   // 完成后的回调
   onComplete: () => {
      console.log("已结束")
   },
   // 开始的回调
   onStart: () => {
      console.log("动画开始")
   }
})

添加点击事件,实现双击运行与暂停动画

// 添加双击事件
window.addEventListener('dblclick', () => {
    // 如果是在运动中,则让他暂停
    if(animate.isActive()) {
        animate.pause()
    }else {
        // 否则让它动起来
        animate.resume()
    }
})
  1. 自适应页面,实现渲染器相机自适应
// 监听页面变化,更新渲染画面
window.addEventListener('resize', () => {
   // 获取当前屏幕宽高
   let windowHeight = window.innerHeight
   let windowWidth = window.innerWidth
   // 更新摄像头
   camera.aspect = windowWidth/windowHeight
   // 更新摄像头投影矩阵
   camera.updateProjectionMatrix()

   // 更新渲染器
   renderer.setSize(windowWidth, windowHeight)
   // 设置渲染器的像素比
   renderer.setPixelRatio(window.devicePixelRatio)
})
  1. 利用JS实现,双击全屏与退出全屏
window.addEventListener('dblclick', () => {
   // 控制全屏与退出全屏
   let fullScreenElement = document.fullscreenElement
   // 如果该对象不存在
   if(!fullScreenElement) {
      // 则取渲染器对象,获取根节点,进入全屏
      renderer.domElement.requestFullscreen()
   }else {
      // 否则退出全屏
      document.exitFullscreen()
   }
})