用three.js写一个下雨动画

最近看了《Three.js开发指南》,深刻地意识到光看不练跟没看差不多,所以就练习写了这个小动画。
在这里插入图片描述
gif 预览地址:https://juejin.cn/post/6940542710709223432

项目地址: https://github.com/alasolala/threejs-tutorial.git

前置知识

WebGL让我们能在浏览器开发3D应用,然而直接使用WebGL编程还是挺复杂的,开发者需要知道WebGL的底层细节,并且学习复杂的着色语言来获得WebGL的大部分功能。Three.js提供了一系列很简单的关于WebGL特性的JavaScript API,使开发者可以很方便地创作出好看的3D图形。在Three.js官网,就有很多酷炫3D效果

使用Three.js开发3D应用,通常要包括渲染器(Renderer)、场景(Scene)、照相机(Camera),以及你在场景中创建的物体,光照。

设想一下照相的情况,我们需要一个场景(Scene),在这个场景中摆好要拍摄的物体,设置光照环境,摆放好照相机(Camera)的位置和朝向,然后就可以拍照了。渲染器(Renderer)可能和摄影师比较像吧,负责下命令拍摄,并且生成图像(照片)。

将下面的代码的复制并运行,就可以得到一个很简单的3D场景。

image.png

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>room</title>
</head>
<body>
  <div id="webgl-output"></div>
  <script src="https://unpkg.com/three@0.119.0/build/three.js"></script>
  <script>
    function init () {
      const scene = new THREE.Scene()

      const camera = new THREE.PerspectiveCamera(45, 
        window.innerWidth / window.innerHeight,
        0.1,
        1000
      )
      camera.position.set(-30, 40, 30)
      camera.lookAt(0,0,0)
      scene.add(camera) 

      const planeGeometry = new THREE.PlaneGeometry(60,20)
      const planeMaterial = new THREE.MeshLambertMaterial({
        color: 0xAAAAAA
      })  
      const plane = new THREE.Mesh(planeGeometry, planeMaterial)
      plane.rotation.x = -Math.PI / 2
      plane.position.set(15, 0, 0)
      scene.add(plane)

      const sphereGeometry = new THREE.SphereGeometry(4, 20, 20)
      const sphereMaterial = new THREE.MeshLambertMaterial({
        color: 0xffff00
      })
      const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial)
      sphere.position.set(20, 4, 2)
      scene.add(sphere)

      const spotLight = new THREE.SpotLight(0xffffff)
      spotLight.position.set(-20, 30, -15)
      scene.add(spotLight)

      const renderer = new THREE.WebGLRenderer()
      renderer.setClearColor(new THREE.Color(0x000000))
      renderer.setSize(window.innerWidth, window.innerHeight)
      document.getElementById('webgl-output').appendChild(renderer.domElement)

      renderer.render(scene, camera)
    }

    init()
</script>
</body>
</html>

场景(Scene

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值