0


圣诞树(动态效果)

一、运行效果

二、制作方法

1.复制代码到Dreamweaver或HBuilder或vscode中

2.点击运行---运行到浏览器---选择你要打开的浏览器

3.打开后会出现这个界面,前四个是固定音乐,最后一个是自主选择的音乐,你可以选择你电脑上的歌曲,什么歌曲都行(第一次打开可能会有点慢,稍等片刻即可,选择音乐的时候点一下没反应的话多点几下即可,第一次打开这属于正常现象)

4.特别提醒:打开的时候电脑一定要处于联网状态

三、源代码

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>圣诞树</title>
  6. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
  7. <style>
  8. * {
  9. box-sizing: border-box;
  10. }
  11. body {
  12. margin: 0;
  13. height: 100vh;
  14. overflow: hidden;
  15. display: flex;
  16. align-items: center;
  17. justify-content: center;
  18. background: #161616;
  19. color: #c5a880;
  20. font-family: sans-serif;
  21. }
  22. label {
  23. display: inline-block;
  24. background-color: #161616;
  25. padding: 16px;
  26. border-radius: 0.3rem;
  27. cursor: pointer;
  28. margin-top: 1rem;
  29. width: 300px;
  30. border-radius: 10px;
  31. border: 1px solid #c5a880;
  32. text-align: center;
  33. }
  34. ul {
  35. list-style-type: none;
  36. padding: 0;
  37. margin: 0;
  38. }
  39. .btn {
  40. background-color: #161616;
  41. border-radius: 10px;
  42. color: #c5a880;
  43. border: 1px solid #c5a880;
  44. padding: 16px;
  45. width: 300px;
  46. margin-bottom: 16px;
  47. line-height: 1.5;
  48. cursor: pointer;
  49. }
  50. .separator {
  51. font-weight: bold;
  52. text-align: center;
  53. width: 300px;
  54. margin: 16px 0px;
  55. color: #a07676;
  56. }
  57. .title {
  58. color: #a07676;
  59. font-weight: bold;
  60. font-size: 1.25rem;
  61. margin-bottom: 16px;
  62. }
  63. .text-loading {
  64. font-size: 2rem;
  65. }
  66. </style>
  67. <script>
  68. window.console = window.console || function (t) { };
  69. </script>
  70. <script>
  71. if (document.location.search.match(/type=embed/gi)) {
  72. window.parent.postMessage("resize", "*");
  73. }
  74. </script>
  75. </head>
  76. <body translate="no">
  77. <script src="https://cdn.jsdelivr.net/npm/three@0.115.0/build/three.min.js"></script>
  78. <script src="https://cdn.jsdelivr.net/npm/three@0.115.0/examples/js/postprocessing/EffectComposer.js"></script>
  79. <script src="https://cdn.jsdelivr.net/npm/three@0.115.0/examples/js/postprocessing/RenderPass.js"></script>
  80. <script src="https://cdn.jsdelivr.net/npm/three@0.115.0/examples/js/postprocessing/ShaderPass.js"></script>
  81. <script src="https://cdn.jsdelivr.net/npm/three@0.115.0/examples/js/shaders/CopyShader.js"></script>
  82. <script src="https://cdn.jsdelivr.net/npm/three@0.115.0/examples/js/shaders/LuminosityHighPassShader.js"></script>
  83. <script src="https://cdn.jsdelivr.net/npm/three@0.115.0/examples/js/postprocessing/UnrealBloomPass.js"></script>
  84. <div id="overlay">
  85. <ul>
  86. <li class="title">请选择音乐</li>
  87. <li>
  88. <button class="btn" id="btnA" type="button">
  89. Snowflakes Falling Down by Simon Panrucker
  90. </button>
  91. </li>
  92. <li><button class="btn" id="btnB" type="button">This Christmas by Dott</button></li>
  93. <li><button class="btn" id="btnC" type="button">No room at the inn by TRG Banks</button></li>
  94. <li><button class="btn" id="btnD" type="button">Jingle Bell Swing by Mark Smeby</button></li>
  95. <li class="separator">或者</li>
  96. <li>
  97. <input type="file" id="upload" hidden />
  98. <label for="upload">Upload File</label>
  99. </li>
  100. </ul>
  101. </div>
  102. <script id="rendered-js">
  103. const { PI, sin, cos } = Math;
  104. const TAU = 2 * PI;
  105. const map = (value, sMin, sMax, dMin, dMax) => {
  106. return dMin + (value - sMin) / (sMax - sMin) * (dMax - dMin);
  107. };
  108. const range = (n, m = 0) =>
  109. Array(n).
  110. fill(m).
  111. map((i, j) => i + j);
  112. const rand = (max, min = 0) => min + Math.random() * (max - min);
  113. const randInt = (max, min = 0) => Math.floor(min + Math.random() * (max - min));
  114. const randChoise = arr => arr[randInt(arr.length)];
  115. const polar = (ang, r = 1) => [r * cos(ang), r * sin(ang)];
  116. let scene, camera, renderer, analyser;
  117. let step = 0;
  118. const uniforms = {
  119. time: { type: "f", value: 0.0 },
  120. step: { type: "f", value: 0.0 }
  121. };
  122. const params = {
  123. exposure: 1,
  124. bloomStrength: 0.9,
  125. bloomThreshold: 0,
  126. bloomRadius: 0.5
  127. };
  128. let composer;
  129. const fftSize = 2048;
  130. const totalPoints = 4000;
  131. const listener = new THREE.AudioListener();
  132. const audio = new THREE.Audio(listener);
  133. document.querySelector("input").addEventListener("change", uploadAudio, false);
  134. const buttons = document.querySelectorAll(".btn");
  135. buttons.forEach((button, index) =>
  136. button.addEventListener("click", () => loadAudio(index)));
  137. function init() {
  138. const overlay = document.getElementById("overlay");
  139. overlay.remove();
  140. scene = new THREE.Scene();
  141. renderer = new THREE.WebGLRenderer({ antialias: true });
  142. renderer.setPixelRatio(window.devicePixelRatio);
  143. renderer.setSize(window.innerWidth, window.innerHeight);
  144. document.body.appendChild(renderer.domElement);
  145. camera = new THREE.PerspectiveCamera(
  146. 60,
  147. window.innerWidth / window.innerHeight,
  148. 1,
  149. 1000);
  150. camera.position.set(-0.09397456774197047, -2.5597086635726947, 24.420789670889008);
  151. camera.rotation.set(0.10443543723052419, -0.003827152981119352, 0.0004011488708739715);
  152. const format = renderer.capabilities.isWebGL2 ?
  153. THREE.RedFormat :
  154. THREE.LuminanceFormat;
  155. uniforms.tAudioData = {
  156. value: new THREE.DataTexture(analyser.data, fftSize / 2, 1, format)
  157. };
  158. addPlane(scene, uniforms, 3000);
  159. addSnow(scene, uniforms);
  160. range(10).map(i => {
  161. addTree(scene, uniforms, totalPoints, [20, 0, -20 * i]);
  162. addTree(scene, uniforms, totalPoints, [-20, 0, -20 * i]);
  163. });
  164. const renderScene = new THREE.RenderPass(scene, camera);
  165. const bloomPass = new THREE.UnrealBloomPass(
  166. new THREE.Vector2(window.innerWidth, window.innerHeight),
  167. 1.5,
  168. 0.4,
  169. 0.85);
  170. bloomPass.threshold = params.bloomThreshold;
  171. bloomPass.strength = params.bloomStrength;
  172. bloomPass.radius = params.bloomRadius;
  173. composer = new THREE.EffectComposer(renderer);
  174. composer.addPass(renderScene);
  175. composer.addPass(bloomPass);
  176. addListners(camera, renderer, composer);
  177. animate();
  178. }
  179. function animate(time) {
  180. analyser.getFrequencyData();
  181. uniforms.tAudioData.value.needsUpdate = true;
  182. step = (step + 1) % 1000;
  183. uniforms.time.value = time;
  184. uniforms.step.value = step;
  185. composer.render();
  186. requestAnimationFrame(animate);
  187. }
  188. function loadAudio(i) {
  189. document.getElementById("overlay").innerHTML =
  190. '<div class="text-loading">正在下载音乐,请稍等...</div>';
  191. const files = [
  192. "https://files.freemusicarchive.org/storage-freemusicarchive-org/music/no_curator/Simon_Panrucker/Happy_Christmas_You_Guys/Simon_Panrucker_-_01_-_Snowflakes_Falling_Down.mp3",
  193. "https://files.freemusicarchive.org/storage-freemusicarchive-org/music/no_curator/Dott/This_Christmas/Dott_-_01_-_This_Christmas.mp3",
  194. "https://files.freemusicarchive.org/storage-freemusicarchive-org/music/ccCommunity/TRG_Banks/TRG_Banks_Christmas_Album/TRG_Banks_-_12_-_No_room_at_the_inn.mp3",
  195. "https://files.freemusicarchive.org/storage-freemusicarchive-org/music/ccCommunity/Mark_Smeby/En_attendant_Nol/Mark_Smeby_-_07_-_Jingle_Bell_Swing.mp3"];
  196. const file = files[i];
  197. const loader = new THREE.AudioLoader();
  198. loader.load(file, function (buffer) {
  199. audio.setBuffer(buffer);
  200. audio.play();
  201. analyser = new THREE.AudioAnalyser(audio, fftSize);
  202. init();
  203. });
  204. }
  205. function uploadAudio(event) {
  206. document.getElementById("overlay").innerHTML =
  207. '<div class="text-loading">请稍等...</div>';
  208. const files = event.target.files;
  209. const reader = new FileReader();
  210. reader.onload = function (file) {
  211. var arrayBuffer = file.target.result;
  212. listener.context.decodeAudioData(arrayBuffer, function (audioBuffer) {
  213. audio.setBuffer(audioBuffer);
  214. audio.play();
  215. analyser = new THREE.AudioAnalyser(audio, fftSize);
  216. init();
  217. });
  218. };
  219. reader.readAsArrayBuffer(files[0]);
  220. }
  221. function addTree(scene, uniforms, totalPoints, treePosition) {
  222. const vertexShader = `
  223. attribute float mIndex;
  224. varying vec3 vColor;
  225. varying float opacity;
  226. uniform sampler2D tAudioData;
  227. float norm(float value, float min, float max ){
  228. return (value - min) / (max - min);
  229. }
  230. float lerp(float norm, float min, float max){
  231. return (max - min) * norm + min;
  232. }
  233. float map(float value, float sourceMin, float sourceMax, float destMin, float destMax){
  234. return lerp(norm(value, sourceMin, sourceMax), destMin, destMax);
  235. }
  236. void main() {
  237. vColor = color;
  238. vec3 p = position;
  239. vec4 mvPosition = modelViewMatrix * vec4( p, 1.0 );
  240. float amplitude = texture2D( tAudioData, vec2( mIndex, 0.1 ) ).r;
  241. float amplitudeClamped = clamp(amplitude-0.4,0.0, 0.6 );
  242. float sizeMapped = map(amplitudeClamped, 0.0, 0.6, 1.0, 20.0);
  243. opacity = map(mvPosition.z , -200.0, 15.0, 0.0, 1.0);
  244. gl_PointSize = sizeMapped * ( 100.0 / -mvPosition.z );
  245. gl_Position = projectionMatrix * mvPosition;
  246. }
  247. `;
  248. const fragmentShader = `
  249. varying vec3 vColor;
  250. varying float opacity;
  251. uniform sampler2D pointTexture;
  252. void main() {
  253. gl_FragColor = vec4( vColor, opacity );
  254. gl_FragColor = gl_FragColor * texture2D( pointTexture, gl_PointCoord );
  255. }
  256. `;
  257. const shaderMaterial = new THREE.ShaderMaterial({
  258. uniforms: {
  259. ...uniforms,
  260. pointTexture: {
  261. value: new THREE.TextureLoader().load(`https://assets.codepen.io/3685267/spark1.png`)
  262. }
  263. },
  264. vertexShader,
  265. fragmentShader,
  266. blending: THREE.AdditiveBlending,
  267. depthTest: false,
  268. transparent: true,
  269. vertexColors: true
  270. });
  271. const geometry = new THREE.BufferGeometry();
  272. const positions = [];
  273. const colors = [];
  274. const sizes = [];
  275. const phases = [];
  276. const mIndexs = [];
  277. const color = new THREE.Color();
  278. for (let i = 0; i < totalPoints; i++) {
  279. const t = Math.random();
  280. const y = map(t, 0, 1, -8, 10);
  281. const ang = map(t, 0, 1, 0, 6 * TAU) + TAU / 2 * (i % 2);
  282. const [z, x] = polar(ang, map(t, 0, 1, 5, 0));
  283. const modifier = map(t, 0, 1, 1, 0);
  284. positions.push(x + rand(-0.3 * modifier, 0.3 * modifier));
  285. positions.push(y + rand(-0.3 * modifier, 0.3 * modifier));
  286. positions.push(z + rand(-0.3 * modifier, 0.3 * modifier));
  287. color.setHSL(map(i, 0, totalPoints, 1.0, 0.0), 1.0, 0.5);
  288. colors.push(color.r, color.g, color.b);
  289. phases.push(rand(1000));
  290. sizes.push(1);
  291. const mIndex = map(i, 0, totalPoints, 1.0, 0.0);
  292. mIndexs.push(mIndex);
  293. }
  294. geometry.setAttribute(
  295. "position",
  296. new THREE.Float32BufferAttribute(positions, 3).setUsage(
  297. THREE.DynamicDrawUsage));
  298. geometry.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3));
  299. geometry.setAttribute("size", new THREE.Float32BufferAttribute(sizes, 1));
  300. geometry.setAttribute("phase", new THREE.Float32BufferAttribute(phases, 1));
  301. geometry.setAttribute("mIndex", new THREE.Float32BufferAttribute(mIndexs, 1));
  302. const tree = new THREE.Points(geometry, shaderMaterial);
  303. const [px, py, pz] = treePosition;
  304. tree.position.x = px;
  305. tree.position.y = py;
  306. tree.position.z = pz;
  307. scene.add(tree);
  308. }
  309. function addSnow(scene, uniforms) {
  310. const vertexShader = `
  311. attribute float size;
  312. attribute float phase;
  313. attribute float phaseSecondary;
  314. varying vec3 vColor;
  315. varying float opacity;
  316. uniform float time;
  317. uniform float step;
  318. float norm(float value, float min, float max ){
  319. return (value - min) / (max - min);
  320. }
  321. float lerp(float norm, float min, float max){
  322. return (max - min) * norm + min;
  323. }
  324. float map(float value, float sourceMin, float sourceMax, float destMin, float destMax){
  325. return lerp(norm(value, sourceMin, sourceMax), destMin, destMax);
  326. }
  327. void main() {
  328. float t = time* 0.0006;
  329. vColor = color;
  330. vec3 p = position;
  331. p.y = map(mod(phase+step, 1000.0), 0.0, 1000.0, 25.0, -8.0);
  332. p.x += sin(t+phase);
  333. p.z += sin(t+phaseSecondary);
  334. opacity = map(p.z, -150.0, 15.0, 0.0, 1.0);
  335. vec4 mvPosition = modelViewMatrix * vec4( p, 1.0 );
  336. gl_PointSize = size * ( 100.0 / -mvPosition.z );
  337. gl_Position = projectionMatrix * mvPosition;
  338. }
  339. `;
  340. const fragmentShader = `
  341. uniform sampler2D pointTexture;
  342. varying vec3 vColor;
  343. varying float opacity;
  344. void main() {
  345. gl_FragColor = vec4( vColor, opacity );
  346. gl_FragColor = gl_FragColor * texture2D( pointTexture, gl_PointCoord );
  347. }
  348. `;
  349. function createSnowSet(sprite) {
  350. const totalPoints = 300;
  351. const shaderMaterial = new THREE.ShaderMaterial({
  352. uniforms: {
  353. ...uniforms,
  354. pointTexture: {
  355. value: new THREE.TextureLoader().load(sprite)
  356. }
  357. },
  358. vertexShader,
  359. fragmentShader,
  360. blending: THREE.AdditiveBlending,
  361. depthTest: false,
  362. transparent: true,
  363. vertexColors: true
  364. });
  365. const geometry = new THREE.BufferGeometry();
  366. const positions = [];
  367. const colors = [];
  368. const sizes = [];
  369. const phases = [];
  370. const phaseSecondaries = [];
  371. const color = new THREE.Color();
  372. for (let i = 0; i < totalPoints; i++) {
  373. const [x, y, z] = [rand(25, -25), 0, rand(15, -150)];
  374. positions.push(x);
  375. positions.push(y);
  376. positions.push(z);
  377. color.set(randChoise(["#f1d4d4", "#f1f6f9", "#eeeeee", "#f1f1e8"]));
  378. colors.push(color.r, color.g, color.b);
  379. phases.push(rand(1000));
  380. phaseSecondaries.push(rand(1000));
  381. sizes.push(rand(4, 2));
  382. }
  383. geometry.setAttribute(
  384. "position",
  385. new THREE.Float32BufferAttribute(positions, 3));
  386. geometry.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3));
  387. geometry.setAttribute("size", new THREE.Float32BufferAttribute(sizes, 1));
  388. geometry.setAttribute("phase", new THREE.Float32BufferAttribute(phases, 1));
  389. geometry.setAttribute(
  390. "phaseSecondary",
  391. new THREE.Float32BufferAttribute(phaseSecondaries, 1));
  392. const mesh = new THREE.Points(geometry, shaderMaterial);
  393. scene.add(mesh);
  394. }
  395. const sprites = [
  396. "https://assets.codepen.io/3685267/snowflake1.png",
  397. "https://assets.codepen.io/3685267/snowflake2.png",
  398. "https://assets.codepen.io/3685267/snowflake3.png",
  399. "https://assets.codepen.io/3685267/snowflake4.png",
  400. "https://assets.codepen.io/3685267/snowflake5.png"];
  401. sprites.forEach(sprite => {
  402. createSnowSet(sprite);
  403. });
  404. }
  405. function addPlane(scene, uniforms, totalPoints) {
  406. const vertexShader = `
  407. attribute float size;
  408. attribute vec3 customColor;
  409. varying vec3 vColor;
  410. void main() {
  411. vColor = customColor;
  412. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  413. gl_PointSize = size * ( 300.0 / -mvPosition.z );
  414. gl_Position = projectionMatrix * mvPosition;
  415. }
  416. `;
  417. const fragmentShader = `
  418. uniform vec3 color;
  419. uniform sampler2D pointTexture;
  420. varying vec3 vColor;
  421. void main() {
  422. gl_FragColor = vec4( vColor, 1.0 );
  423. gl_FragColor = gl_FragColor * texture2D( pointTexture, gl_PointCoord );
  424. }
  425. `;
  426. const shaderMaterial = new THREE.ShaderMaterial({
  427. uniforms: {
  428. ...uniforms,
  429. pointTexture: {
  430. value: new THREE.TextureLoader().load(`https://assets.codepen.io/3685267/spark1.png`)
  431. }
  432. },
  433. vertexShader,
  434. fragmentShader,
  435. blending: THREE.AdditiveBlending,
  436. depthTest: false,
  437. transparent: true,
  438. vertexColors: true
  439. });
  440. const geometry = new THREE.BufferGeometry();
  441. const positions = [];
  442. const colors = [];
  443. const sizes = [];
  444. const color = new THREE.Color();
  445. for (let i = 0; i < totalPoints; i++) {
  446. const [x, y, z] = [rand(-25, 25), 0, rand(-150, 15)];
  447. positions.push(x);
  448. positions.push(y);
  449. positions.push(z);
  450. color.set(randChoise(["#93abd3", "#f2f4c0", "#9ddfd3"]));
  451. colors.push(color.r, color.g, color.b);
  452. sizes.push(1);
  453. }
  454. geometry.setAttribute(
  455. "position",
  456. new THREE.Float32BufferAttribute(positions, 3).setUsage(
  457. THREE.DynamicDrawUsage));
  458. geometry.setAttribute(
  459. "customColor",
  460. new THREE.Float32BufferAttribute(colors, 3));
  461. geometry.setAttribute("size", new THREE.Float32BufferAttribute(sizes, 1));
  462. const plane = new THREE.Points(geometry, shaderMaterial);
  463. plane.position.y = -8;
  464. scene.add(plane);
  465. }
  466. function addListners(camera, renderer, composer) {
  467. document.addEventListener("keydown", e => {
  468. const { x, y, z } = camera.position;
  469. console.log(`camera.position.set(${x},${y},${z})`);
  470. const { x: a, y: b, z: c } = camera.rotation;
  471. console.log(`camera.rotation.set(${a},${b},${c})`);
  472. });
  473. window.addEventListener(
  474. "resize",
  475. () => {
  476. const width = window.innerWidth;
  477. const height = window.innerHeight;
  478. camera.aspect = width / height;
  479. camera.updateProjectionMatrix();
  480. renderer.setSize(width, height);
  481. composer.setSize(width, height);
  482. },
  483. false);
  484. }
  485. </script>
  486. </body>
  487. </html>
标签: html javascript 前端

本文转载自: https://blog.csdn.net/xiongIT/article/details/128286188
版权归原作者 杨乙燃5132 所有, 如有侵权,请联系我们删除。

“圣诞树(动态效果)”的评论:

还没有评论