-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThreeWorld.js
103 lines (88 loc) · 2.35 KB
/
ThreeWorld.js
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
import {
DirectionalLight,
BoxGeometry,
Clock,
Mesh,
PerspectiveCamera,
Scene,
WebGLRenderer,
MeshToonMaterial,
} from 'three';
const sizes = {
width: window.innerWidth,
height: window.innerHeight,
};
class ThreeWorld {
scene = new Scene();
clock = new Clock();
camera = new PerspectiveCamera(35, sizes.width / sizes.height, 0.1, 100);
directionalLight = new DirectionalLight('#fff', 1);
objects = [];
renderer;
offsetY = 0;
objectDistance = 4;
constructor(canvas, scrollbar, sections) {
this.renderer = new WebGLRenderer({
canvas,
alpha: true,
});
this.scrollbar = scrollbar;
this.sections = sections;
}
configRenderer() {
this.renderer.setSize(sizes.width, sizes.height);
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
configCamera() {
this.camera.position.z = 6;
this.scene.add(this.camera);
}
configDirectionalLight() {
this.directionalLight.position.set(1, 1, 0);
this.scene.add(this.directionalLight);
}
createObject() {
const geometry = new BoxGeometry(1, 1, 1);
const material = new MeshToonMaterial({ color: '#5c1c64' });
const mesh = new Mesh(geometry, material);
mesh.position.x = -1;
this.objects.push(mesh);
mesh.position.y = -this.objectDistance * (this.objects.length - 1);
this.scene.add(mesh);
}
createObjects() {
for (let i = 0; i < this.sections.length; i++) {
this.createObject();
}
}
onSroll() {
this.scrollbar.addListener((status) => {
this.offsetY = status.offset.y;
});
}
onResize() {
window.addEventListener('resize', () => {
sizes.width = window.innerWidth;
sizes.height = window.innerHeight;
this.camera.aspect = sizes.width / sizes.height;
this.camera.updateProjectionMatrix();
this.renderer.setSize(sizes.width, sizes.height);
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
}
tick() {
this.camera.position.y = (-this.offsetY / sizes.height) * this.objectDistance;
this.renderer.render(this.scene, this.camera);
window.requestAnimationFrame(this.tick.bind(this));
}
init() {
this.onResize();
this.configCamera();
this.configRenderer();
this.configDirectionalLight();
this.tick();
this.onSroll();
this.createObjects();
}
}
export default ThreeWorld;