【可视化学习】10-Three.js全屏滚动
发表于:2023-05-27 |

今天一起学习网上看到的滚动3d动画效果,因为本人技术有限,只能给出一些比较简单的案例用来滚动,后续学到好玩的案例可以和大家再一起分享

投射光线基础代码

首先我们拿一下上一篇文章中的投射光线效果代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import * as THREE from "three";
// 导入轨道控制器
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

// 1、创建场景
const scene = new THREE.Scene();

// 2、创建相机
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
300
);

// 设置相机位置
camera.position.set(0, 0, 20);
scene.add(camera);

const cubeGeometry = new THREE.BoxBufferGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({
wireframe: true,
});
const redMaterial = new THREE.MeshBasicMaterial({
color: "#ff0000",
});

// 1000立方体
let cubeArr = [];
for (let i = -5; i < 5; i++) {
for (let j = -5; j < 5; j++) {
for (let z = -5; z < 5; z++) {
const cube = new THREE.Mesh(cubeGeometry, material);
cube.position.set(i, j, z);
scene.add(cube);
cubeArr.push(cube);
}
}
}

// 创建投射光线对象
const raycaster = new THREE.Raycaster();

// 鼠标的位置对象
const mouse = new THREE.Vector2();

// 监听鼠标的位置
window.addEventListener("click", (event) => {
// console.log(event);
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -((event.clientY / window.innerHeight) * 2 - 1);
raycaster.setFromCamera(mouse, camera);
let result = raycaster.intersectObjects(cubeArr);
// console.log(result);
// result[0].object.material = redMaterial;
result.forEach((item) => {
item.object.material = redMaterial;
});
});

// 初始化渲染器
const renderer = new THREE.WebGLRenderer();
// 设置渲染的尺寸大小
renderer.setSize(window.innerWidth, window.innerHeight);
// 开启场景中的阴影贴图
renderer.shadowMap.enabled = true;
renderer.physicallyCorrectLights = true;

// console.log(renderer);
// 将webgl渲染的canvas内容添加到body
document.body.appendChild(renderer.domElement);

// 创建轨道控制器
const controls = new OrbitControls(camera, renderer.domElement);
// 设置控制器阻尼,让控制器更有真实效果,必须在动画循环里调用.update()。
controls.enableDamping = true;

// 添加坐标轴辅助器
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);

function render() {
controls.update();
renderer.render(scene, camera);
// 渲染下一帧的时候就会调用render函数
requestAnimationFrame(render);
}

render();

// 监听画面变化,更新渲染画面
window.addEventListener("resize", () => {
// console.log("画面变化了");

// 更新摄像头
camera.aspect = window.innerWidth / window.innerHeight;
// 更新摄像机的投影矩阵
camera.updateProjectionMatrix();

// 更新渲染器
renderer.setSize(window.innerWidth, window.innerHeight);
// 设置渲染器的像素比
renderer.setPixelRatio(window.devicePixelRatio);
});

效果图

更换背景色

接下来,我们换个背景色

1
2
3
body {
background-color: rgb(36, 58, 66);
}

我们可以看到,没有生效,因为我们没有把渲染器的背景色设置为透明
1
2
// 初始化渲染器
const renderer = new THREE.WebGLRenderer({ alpha: true });

效果图

立方体添加自动旋转

给立方体添加自动旋转

创建一个组,将立方体添加到组中,将组添加到场景中

1
2
3
4
5
6
7
8
9
10
11
12
13
let cubeArr = [];
let cubeGroup = new THREE.Group();
for (let i = -5; i < 5; i++) {
for (let j = -5; j < 5; j++) {
for (let z = -5; z < 5; z++) {
const cube = new THREE.Mesh(cubeGeometry, material);
cube.position.set(i, j, z);
cubeGroup.add(cube);
cubeArr.push(cube);
}
}
}
scene.add(cubeGroup);

创建时间函数,每次render调用

1
2
3
4
5
6
7
8
9
10
11
12
// 设置时钟
const clock = new THREE.Clock();
function render() {
let time = clock.getElapsedTime();
cubeGroup.rotation.x = time * 0.5;
cubeGroup.rotation.y = time * 0.5;
controls.update();
renderer.render(scene, camera);
// 渲染下一帧的时候就会调用render函数
requestAnimationFrame(render);
}
render();

效果图

添加文字

html中添加以下内容

1
2
3
4
5
6
7
8
9
10
11
12
<div class="page page0">
<h1>Ray投射光线</h1>
<h3>THREE.Raycaster实现3d交互效果</h3>
</div>
<div class="page page1">
<h1>THREE.BufferGeometry!</h1>
<h3>应用打造酷炫的三角形</h3>
</div>
<div class="page page2">
<h1>活泼点光源</h1>
<h3>点光源围绕照亮小球</h3>
</div>

css中添加以下内容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* 已有 */
* {
margin: 0;
padding: 0;
}
body {
background-color: rgb(36, 58, 66);
}
canvas {
position: fixed;
left: 0;
top: 0;
}
/* 新增 */
.page {
height: 100vh;
display: flex;
color: #fff;
flex-direction: column;
align-items: center;
position: relative;
z-index: 10;
}
.page h1 {
margin: 60px;
font-size: 40px;
}

.page h3 {
font-size: 30px;
}
::-webkit-scrollbar {
display: none;
}

效果图

demo引入

我们把之前写过的demo引入

引入酷炫三角形

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 创建三角形酷炫物体
// 添加物体
// 创建几何体
var sjxGroup = new THREE.Group();
for (let i = 0; i < 50; i++) {
// 每一个三角形,需要3个顶点,每个顶点需要3个值
const geometry = new THREE.BufferGeometry();
const positionArray = new Float32Array(9);
for (let j = 0; j < 9; j++) {
if (j % 3 == 1) {
positionArray[j] = Math.random() * 10 - 5;
} else {
positionArray[j] = Math.random() * 10 - 5;
}
}
geometry.setAttribute(
"position",
new THREE.BufferAttribute(positionArray, 3)
);
let color = new THREE.Color(Math.random(), Math.random(), Math.random());
const material = new THREE.MeshBasicMaterial({
color: color,
transparent: true,
opacity: 0.5,
side: THREE.DoubleSide,
});
// 根据几何体和材质创建物体
let sjxMesh = new THREE.Mesh(geometry, material);
sjxGroup.add(sjxMesh);
}
// 设置位置,我们以30为一个屏幕
sjxGroup.position.set(0, -30, 0);
scene.add(sjxGroup);

引入弹跳小球demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// 弹跳小球
const sphereGroup = new THREE.Group();
const sphereGeometry = new THREE.SphereBufferGeometry(1, 20, 20);
const spherematerial = new THREE.MeshStandardMaterial({
side: THREE.DoubleSide,
});
const sphere = new THREE.Mesh(sphereGeometry, spherematerial);
// 投射阴影
sphere.castShadow = true;

sphereGroup.add(sphere);

// 创建平面
const planeGeometry = new THREE.PlaneBufferGeometry(20, 20);
const plane = new THREE.Mesh(planeGeometry, spherematerial);
plane.position.set(0, -1, 0);
plane.rotation.x = -Math.PI / 2;
// 接收阴影
plane.receiveShadow = true;
sphereGroup.add(plane);

// 灯光
// 环境光
const light = new THREE.AmbientLight(0xffffff, 0.5); // soft white light
sphereGroup.add(light);

const smallBall = new THREE.Mesh(
new THREE.SphereBufferGeometry(0.1, 20, 20),
new THREE.MeshBasicMaterial({ color: 0xff0000 })
);
smallBall.position.set(2, 2, 2);
//直线光源
const pointLight = new THREE.PointLight(0xff0000, 3);
// pointLight.position.set(2, 2, 2);
pointLight.castShadow = true;

// 设置阴影贴图模糊度
pointLight.shadow.radius = 20;
// 设置阴影贴图的分辨率
pointLight.shadow.mapSize.set(512, 512);

// 设置透视相机的属性
smallBall.add(pointLight);
sphereGroup.add(smallBall);
// 设置位置,我们以30为一个屏幕
sphereGroup.position.set(0, -60, 0);
scene.add(sphereGroup);

引入之后,我们发现我们的案例没法滚动了,被锁定死了,这时候我们需要想起来,在3d中,移动场景本质上是移动相机(即我们的眼睛)

根据滚动移动相机

注意事项,我们需要将controls.update()注释掉,不然会导致物体的放大缩小无法正常滚动展示

1
2
3
4
5
6
7
8
9
10
11
12
13
// 设置时钟
const clock = new THREE.Clock();
function render() {
let time = clock.getElapsedTime();
cubeGroup.rotation.x = time * 0.5;
cubeGroup.rotation.y = time * 0.5;
// 根据当前滚动的scrolly,去设置相机移动的位置(相除得到滚动了几个30)
camera.position.y = -(window.scrollY / window.innerHeight) * 30;
// controls.update();
renderer.render(scene, camera);
// 渲染下一帧的时候就会调用render函数
requestAnimationFrame(render);
}

效果图

给另外俩个demo添加自动旋转

根据之前的旋转,给三角形和小球的demo也加上旋转效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function render() {
let time = clock.getElapsedTime();
cubeGroup.rotation.x = time * 0.5;
cubeGroup.rotation.y = time * 0.5;

sjxGroup.rotation.x = time * 0.4;
sjxGroup.rotation.z = time * 0.3;

smallBall.position.x = Math.sin(time) * 3;
smallBall.position.z = Math.cos(time) * 3;
smallBall.position.y = 2 + Math.sin(time * 10) / 2;
sphereGroup.rotation.z = Math.sin(time) * 0.05;
sphereGroup.rotation.x = Math.sin(time) * 0.05;
// 根据当前滚动的scrolly,去设置相机移动的位置
camera.position.y = -(window.scrollY / window.innerHeight) * 30;
renderer.render(scene, camera);
// 渲染下一帧的时候就会调用render函数
requestAnimationFrame(render);
}

效果图

使用gsap动画替换render中的动画

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// 导入动画库
import gsap from "gsap";
gsap.to(cubeGroup.rotation, {
x: "+=" + Math.PI * 2,
y: "+=" + Math.PI * 2,
duration: 10,
ease: "power2.inOut",
repeat: -1,
});
gsap.to(sjxGroup.rotation, {
x: "-=" + Math.PI * 2,
z: "+=" + Math.PI * 2,
duration: 12,
ease: "power2.inOut",
repeat: -1,
});
gsap.to(smallBall.position, {
x: -3,
duration: 6,
ease: "power2.inOut",
repeat: -1,
yoyo: true,
});
gsap.to(smallBall.position, {
y: 0,
duration: 0.5,
ease: "power2.inOut",
repeat: -1,
yoyo: true,
});

效果图

添加滚动旋转文字内容

滚动监听第几个页面从而完成旋转文字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
let arrGroup = [cubeGroup, sjxGroup, sphereGroup];
// 设置当前页
let currentPage = 0;
// 监听滚动事件
window.addEventListener("scroll", () => {
// console.log(window.scrollY);
const newPage = Math.round(window.scrollY / window.innerHeight);
if (newPage != currentPage) {
currentPage = newPage;
console.log("改变页面,当前是:" + currentPage);
console.log(arrGroup[currentPage].rotation);
gsap.to(arrGroup[currentPage].rotation, {
z: "+=" + Math.PI * 2,
x: "+=" + Math.PI * 2,
duration: 2,
onComplete: () => {
console.log("旋转完成");
},
});

// gsap.to(`.page${currentPage} h1`, {
// rotate: "+=360",
// duration: 1,
// });
gsap.fromTo(
`.page${currentPage} h1`,
{ x: -300 },
{ x: 0, rotate: "+=360", duration: 1 }
);
}
});

效果图

添加鼠标滑过水平移动效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 监听鼠标的位置
window.addEventListener("mousemove", (event) => {
mouse.x = event.clientX / window.innerWidth - 0.5;
mouse.y = event.clientY / window.innerHeight - 0.5;
});
function render() {
// 两次render的间隔时间
let deltaTime = clock.getDelta();
// 根据当前滚动的scrolly,去设置相机移动的位置
camera.position.y = -(window.scrollY / window.innerHeight) * 30;
// 根据间隔时间去延迟更新相机的位置,从而产生阻尼效果
camera.position.x += (mouse.x * 10 - camera.position.x) * deltaTime * 5;
renderer.render(scene, camera);
// 渲染下一帧的时候就会调用render函数
requestAnimationFrame(render);
}

到此为止,本个案例就完成了,效果图如下:
效果图

上一篇:
【可视化学习】11-Three.js物理引擎
下一篇:
组件记录-图片裁剪组件