小白也看得懂的用three.js实现粒子移动

997 阅读2分钟

写在前面

作为一个前端新人,你必须要知道的基础是web前端三件套(Html,Css,Javascript)

  • Html:专门用于绘制页面的元素,在页面上要看得到东西,它要是html结构。
  • Css:用于去修饰一些html结构的样式。
  • Javascript:结合html和css去实现用户交互的一些行为。

这篇文章我们就用这三件套来实现下面粒子化的图示效果:

1.gif

准备工作

  1. vscode编辑器

  2. 在html中导入three.js

<script src="https://cdn.bootcdn.net/ajax/libs/three.js/0.150.1/three.js"></script>

它是一个WebGL引擎,基于JavaScript,可直接运行GPU驱动游戏与图形驱动应用于浏览器。其库提供大量特性与API以绘制3D场景于浏览器。

开始

  1. 在html中放置一个容器container,并设置一定的样式。
<style>
        * {
            margin: 0;
            padding: 0;
        }

        html,
        body {
            width: 100%;
            height: 100%;
        }

        #container {
            color: red;
            width: 100%;
            height: 100%;
        }
    </style>
  1. 接下来就是整个项目的灵魂了,编写Js
let scene //定义一个场景
let camear//定义一个摄相机
let renderer//定义渲染器
let material//定义材质
let mouseX = 0
let mouseY = 0

function init() {
    //创建一个摄相机
    camear = new THREE.PerspectiveCamera()
    //摄像机摆放位置
    camear.position.z = 500
    //搭建场景
    scene = new THREE.Scene();
    //添加雾化效果
    scene.fog = new THREE.FogExp2(0x000ff, 0.001)
    //创建一个模型
    const geometry = new THREE.BufferGeometry()

    var vertices = []
    //创建n个正方形,也就是效果图中的粒子
    const size = 2000

    for (let i = 0; i < 20000; i++) {
        //粒子是随机生成的,坐标不一样,3D效果
        const x = (Math.random() * size + Math.random() * size) / 2 - size / 2
        const y = (Math.random() * size + Math.random() * size) / 2 - size / 2
        const z = (Math.random() * size + Math.random() * size) / 2 - size / 2
        vertices.push(x, y, z)
    }
    //为粒子设置位置属性
    geometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3))
    //创建材质反光
    material = new THREE.PointsMaterial({
        size: 2,
        color: 0xffffff
    })
    //将材质用到模型上去
    const particles = new THREE.Points(geometry, material)
    //添加到场景中
    scene.add(particles)
    //渲染器把场景变成可渲染的
    renderer = new THREE.WebGLRenderer()
    renderer.setPixelRatio(window.devicePixelRatio)
    renderer.setSize(window.innerWidth, window.innerHeight)
    //渲染器渲染场景和摄影机
    renderer.render(scene, camear)
    //获取容器,添加渲染器
    document.getElementById('container').appendChild(renderer.domElement)
    //鼠标移动事件
    document.getElementById('container').addEventListener('pointermove', onPointerMove)

}
init()
animate()


function animate() {
    // 控制摄像头动起来
    requestAnimationFrame(animate)//递归
    render()
}
function render() {
    camear.position.x += (mouseX * 2 - camear.position.x) * 0.02
    camear.position.y += (-mouseY * 2 - camear.position.y) * 0.02
    camear.lookAt(scene.position)
    renderer.render(scene, camear)
    scene.rotation.x += 0.001
    scene.rotation.y += 0.002
}

//鼠标移动
function onPointerMove(event) {
    mouseX = event.clientX - (window.innerWidth / 2)
    mouseY = event.clientY - (window.innerHeight / 2)
}
  1. 最后只需要将这份Js引入到html中就可以了。

最后

这个粒子化的效果我们可以用在网站或博客上,当然还有一些更加炫酷的效果展示值得我们去学习实现。