马黑PHP整站系统

three.js : 与音频联动的球体动画

位置: 首页 > 前端三套件[ 发布时间: 2025.5.10  作者: 马黑  阅读: 31 ]
<audio id="aud" src="https://music.163.com/song/media/outer/url?id=1464843172" autoplay loop controls></audio>

<script type="module">

import * as THREE from 'https://esm.sh/three';
import { OrbitControls } from "https://esm.sh/three/examples/jsm/controls/OrbitControls";

let rotRaf, isPaused = true;

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 20;
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const geometry = new THREE.SphereGeometry(2, 32, 32, 0, 2 * Math.PI, 0, 2 * Math.PI);
for (let i = 0; i <= 8; i++) {
	const material = new THREE.MeshNormalMaterial({
		transparent: true,
		opacity: 0.6,
		side: THREE.DoubleSide
	});
	const ball = new THREE.Mesh(geometry, material);
	const radian = (360 / 8) * (Math.PI / 180);
	if (i < 8) ball.position.set(8 * Math.sin(radian * i), 8 * Math.cos(radian * i), 0);
	scene.add(ball);
}

const controls = new OrbitControls(camera, renderer.domElement);
controls.enablePan = true;
controls.maxPolarAngle = 1.5;
controls.minPolarAngle = 0.0;
controls.autoRotate = true;
controls.dampingFactor = 0.5;

isPaused = aud.paused;

const mState = () => {
	isPaused = aud.paused;
	aud.paused ? cancelAnimationFrame(rotRaf) : rotating();
};

const rotating = () => {
	if (isPaused ) return;
	controls.update();
	renderer.render(scene, camera);
	rotRaf = requestAnimationFrame(rotating);
};

aud.onplaying = aud.onpause = () => mState();
aud.onseeked = () => cancelAnimationFrame(rotRaf);

rotating();

</script>

<style>
	body { margin: 0; }
	audio { position: absolute; bottom: 20px; right: 20px; }
</style>

前一篇: 使用three.js画一条水平线
下一篇: three.js材质汇总

发表评论:

       

评论列表 [2条]

#2 | 悄然 于 2025-5-10 17:53 发布: 它直接跟音乐联接起来了,点击可控球体暂停。它真的可以用到贴子里去了。。感觉代码会一如既往的复杂,现在看看去。。

#1 | 飞飞 于 2025-5-10 17:52 发布: 这个球体比我想象中的更真实耶。。闪亮闪亮的,还是半透明的。。移动的时候,能通过一个球身看到别的球体。。赞。。

Copyright © 2023 All Right Reserved 马黑PHP文章管理整站系统v1.8
联系我们: gxblk@163.com