最终效果如下:
html代码
<!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>Document</title>
</head>
<body>
<script type="importmap">
{
"imports": {
"three": "../../three/build/three.module.js",
"three/addons/": "../../three/examples/jsm/"
}
}
</script>
<script type="module" src="./index.js">
</script>
</body>
</html>
index.js代码:
import * as THREE from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
const width = 800;
const height = 500;
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
45,
width / height,
0.1,
1000
);
camera.position.set(100, 100, 100);
camera.lookAt(0, 0, 0);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height);
document.body.appendChild(renderer.domElement);
// 粒子
const arr = [];
const N = 5000;
for (let i = 0; i < N; i++) {
const x = 300 * Math.random(0, 1) - 80;
const y = 300 * Math.random(0, 1) - 80;
const z = 300 * Math.random(0, 1) - 80;
arr.push(new THREE.Vector3(x, y, z));
}
const geometry = new THREE.BufferGeometry();
geometry.setFromPoints(arr);
const loader = new THREE.TextureLoader();
const texture = loader.load("./stars.png");
const material = new THREE.PointsMaterial({
color: 0x4d76cf,
map: texture,
transparent: true,
opacity: 1,
sizeAttenuation:true
})
const point = new THREE.Points(geometry, material);
scene.add(point);
// 粒子球
const sphereGeometry = new THREE.SphereGeometry(30,30,30);
const material2 = new THREE.PointsMaterial({
color:0x4d76cf
});
const sphere = new THREE.Points(sphereGeometry,material2)
scene.add(sphere);
const OrbitControl = new OrbitControls(camera, renderer.domElement);
function render() {
point.rotation.y += 0.001;
sphere.rotation.y += 0.005;
requestAnimationFrame(render);
renderer.render(scene, camera);
}
render()
刚开始学习three.js,写的不好请多担待!