使用html+css+js+three.js写圣诞树

实现效果:

<head><meta charset="UTF-8"><title>Musical Christmas Lights</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css"><style>* {box-sizing: border-box;}body {margin: 0;height: 100vh;overflow: hidden;display: flex;align-items: center;justify-content: center;background: #161616;color: #c5a880;font-family: sans-serif;}label {display: inline-block;background-color: #161616;padding: 16px;border-radius: 0.3rem;cursor: pointer;margin-top: 1rem;width: 300px;border-radius: 10px;border: 1px solid #c5a880;text-align: center;}ul {list-style-type: none;padding: 0;margin: 0;}.btn {background-color: #161616;border-radius: 10px;color: #c5a880;border: 1px solid #c5a880;padding: 16px;width: 300px;margin-bottom: 16px;line-height: 1.5;cursor: pointer;}.separator {font-weight: bold;text-align: center;width: 300px;margin: 16px 0px;color: #a07676;}.title {color: #a07676;font-weight: bold;font-size: 1.25rem;margin-bottom: 16px;}.text-loading {font-size: 2rem;}</style><script>window.console = window.console || function(t) {};</script><script>if (document.location.search.match(/type=embed/gi)) {window.parent.postMessage("resize", "*");}</script></head><body translate="no"><script src="https://cdn.jsdelivr.net/npm/three@0.115.0/build/three.min.js"></script><script src="https://cdn.jsdelivr.net/npm/three@0.115.0/examples/js/postprocessing/EffectComposer.js"></script><script src="https://cdn.jsdelivr.net/npm/three@0.115.0/examples/js/postprocessing/RenderPass.js"></script><script src="https://cdn.jsdelivr.net/npm/three@0.115.0/examples/js/postprocessing/ShaderPass.js"></script><script src="https://cdn.jsdelivr.net/npm/three@0.115.0/examples/js/shaders/CopyShader.js"></script><script src="https://cdn.jsdelivr.net/npm/three@0.115.0/examples/js/shaders/LuminosityHighPassShader.js"></script><script src="https://cdn.jsdelivr.net/npm/three@0.115.0/examples/js/postprocessing/UnrealBloomPass.js"></script><div id="overlay"><ul><!-- <li class="title">请选择音乐</li> --><li><button class="btn" id="btnA" type="button">点击</button></li><li><button class="btn" id="btnB" type="button">This Christmas by Dott</button></li> <li><button class="btn" id="btnC" type="button">No room at the inn by TRG Banks</button></li> <li><button class="btn" id="btnD" type="button">Jingle Bell Swing by Mark Smeby</button></li><li class="separator">或者</li><li><input type="file" id="upload" hidden /><label for="upload">上传音乐</label></li></ul></div><script id="rendered-js">const {PI,sin,cos} = Math;const TAU = 2 * PI;const map = (value, sMin, sMax, dMin, dMax) => {return dMin + (value - sMin) / (sMax - sMin) * (dMax - dMin);};const range = (n, m = 0) =>Array(n).fill(m).map((i, j) => i + j);const rand = (max, min = 0) => min + Math.random() * (max - min);const randInt = (max, min = 0) => Math.floor(min + Math.random() * (max - min));const randChoise = arr => arr[randInt(arr.length)];const polar = (ang, r = 1) => [r * cos(ang), r * sin(ang)];let scene, camera, renderer, analyser;let step = 0;const uniforms = {time: {type: "f",value: 0.0},step: {type: "f",value: 0.0}};const params = {exposure: 1,bloomStrength: 0.9,bloomThreshold: 0,bloomRadius: 0.5};let composer;const fftSize = 2048;const totalPoints = 4000;const listener = new THREE.AudioListener();const audio = new THREE.Audio(listener);document.querySelector("input").addEventListener("change", uploadAudio, false);const buttons = document.querySelectorAll(".btn");buttons.forEach((button, index) =>button.addEventListener("click", () => loadAudio(index)));function init() {const overlay = document.getElementById("overlay");overlay.remove();scene = new THREE.Scene();renderer = new THREE.WebGLRenderer({antialias: true});renderer.setPixelRatio(window.devicePixelRatio);renderer.setSize(window.innerWidth, window.innerHeight);document.body.appendChild(renderer.domElement);camera = new THREE.PerspectiveCamera(60,window.innerWidth / window.innerHeight,1,1000);camera.position.set(-0.09397456774197047, -2.5597086635726947, 24.420789670889008);camera.rotation.set(0.10443543723052419, -0.003827152981119352, 0.0004011488708739715);const format = renderer.capabilities.isWebGL2 ?THREE.RedFormat :THREE.LuminanceFormat;uniforms.tAudioData = {value: new THREE.DataTexture(analyser.data, fftSize / 2, 1, format)};addPlane(scene, uniforms, 3000);addSnow(scene, uniforms);range(10).map(i => {addTree(scene, uniforms, totalPoints, [20, 0, -20 * i]);addTree(scene, uniforms, totalPoints, [-20, 0, -20 * i]);});const renderScene = new THREE.RenderPass(scene, camera);const bloomPass = new THREE.UnrealBloomPass(new THREE.Vector2(window.innerWidth, window.innerHeight),1.5,0.4,0.85);bloomPass.threshold = params.bloomThreshold;bloomPass.strength = params.bloomStrength;bloomPass.radius = params.bloomRadius;composer = new THREE.EffectComposer(renderer);composer.addPass(renderScene);composer.addPass(bloomPass);addListners(camera, renderer, composer);animate();}function animate(time) {analyser.getFrequencyData();uniforms.tAudioData.value.needsUpdate = true;step = (step + 1) % 1000;uniforms.time.value = time;uniforms.step.value = step;composer.render();requestAnimationFrame(animate);}function loadAudio(i) {document.getElementById("overlay").innerHTML ='<div class="text-loading">等一下哈 马上来啦...</div>';const files = ["https://files.freemusicarchive.org/storage-freemusicarchive-org/music/no_curator/Simon_Panrucker/Happy_Christmas_You_Guys/Simon_Panrucker_-_01_-_Snowflakes_Falling_Down.mp3","https://files.freemusicarchive.org/storage-freemusicarchive-org/music/no_curator/Dott/This_Christmas/Dott_-_01_-_This_Christmas.mp3","https://files.freemusicarchive.org/storage-freemusicarchive-org/music/ccCommunity/TRG_Banks/TRG_Banks_Christmas_Album/TRG_Banks_-_12_-_No_room_at_the_inn.mp3","https://files.freemusicarchive.org/storage-freemusicarchive-org/music/ccCommunity/Mark_Smeby/En_attendant_Nol/Mark_Smeby_-_07_-_Jingle_Bell_Swing.mp3"];const file = files[i];const loader = new THREE.AudioLoader();loader.load(file, function(buffer) {audio.setBuffer(buffer);audio.play();analyser = new THREE.AudioAnalyser(audio, fftSize);init();});}function uploadAudio(event) {document.getElementById("overlay").innerHTML ='<div class="text-loading">等一下哈 马上来啦...</div>';const files = event.target.files;const reader = new FileReader();reader.onload = function(file) {var arrayBuffer = file.target.result;listener.context.decodeAudioData(arrayBuffer, function(audioBuffer) {audio.setBuffer(audioBuffer);audio.play();analyser = new THREE.AudioAnalyser(audio, fftSize);init();});};reader.readAsArrayBuffer(files[0]);}function addTree(scene, uniforms, totalPoints, treePosition) {const vertexShader = `attribute float mIndex;varying vec3 vColor;varying float opacity;uniform sampler2D tAudioData;float norm(float value, float min, float max ){return (value - min) / (max - min);}float lerp(float norm, float min, float max){return (max - min) * norm + min;}float map(float value, float sourceMin, float sourceMax, float destMin, float destMax){return lerp(norm(value, sourceMin, sourceMax), destMin, destMax);}void main() {vColor = color;vec3 p = position;vec4 mvPosition = modelViewMatrix * vec4( p, 1.0 );float amplitude = texture2D( tAudioData, vec2( mIndex, 0.1 ) ).r;float amplitudeClamped = clamp(amplitude-0.4,0.0, 0.6 );float sizeMapped = map(amplitudeClamped, 0.0, 0.6, 1.0, 20.0);opacity = map(mvPosition.z , -200.0, 15.0, 0.0, 1.0);gl_PointSize = sizeMapped * ( 100.0 / -mvPosition.z );gl_Position = projectionMatrix * mvPosition;}`;const fragmentShader = `varying vec3 vColor;varying float opacity;uniform sampler2D pointTexture;void main() {gl_FragColor = vec4( vColor, opacity );gl_FragColor = gl_FragColor * texture2D( pointTexture, gl_PointCoord ); }`;const shaderMaterial = new THREE.ShaderMaterial({uniforms: {...uniforms,pointTexture: {value: new THREE.TextureLoader().load(`https://assets.codepen.io/3685267/spark1.png`)}},vertexShader,fragmentShader,blending: THREE.AdditiveBlending,depthTest: false,transparent: true,vertexColors: true});const geometry = new THREE.BufferGeometry();const positions = [];const colors = [];const sizes = [];const phases = [];const mIndexs = [];const color = new THREE.Color();for (let i = 0; i < totalPoints; i++) {const t = Math.random();const y = map(t, 0, 1, -8, 10);const ang = map(t, 0, 1, 0, 6 * TAU) + TAU / 2 * (i % 2);const [z, x] = polar(ang, map(t, 0, 1, 5, 0));const modifier = map(t, 0, 1, 1, 0);positions.push(x + rand(-0.3 * modifier, 0.3 * modifier));positions.push(y + rand(-0.3 * modifier, 0.3 * modifier));positions.push(z + rand(-0.3 * modifier, 0.3 * modifier));color.setHSL(map(i, 0, totalPoints, 1.0, 0.0), 1.0, 0.5);colors.push(color.r, color.g, color.b);phases.push(rand(1000));sizes.push(1);const mIndex = map(i, 0, totalPoints, 1.0, 0.0);mIndexs.push(mIndex);}geometry.setAttribute("position",new THREE.Float32BufferAttribute(positions, 3).setUsage(THREE.DynamicDrawUsage));geometry.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3));geometry.setAttribute("size", new THREE.Float32BufferAttribute(sizes, 1));geometry.setAttribute("phase", new THREE.Float32BufferAttribute(phases, 1));geometry.setAttribute("mIndex", new THREE.Float32BufferAttribute(mIndexs, 1));const tree = new THREE.Points(geometry, shaderMaterial);const [px, py, pz] = treePosition;tree.position.x = px;tree.position.y = py;tree.position.z = pz;scene.add(tree);}function addSnow(scene, uniforms) {const vertexShader = `attribute float size;attribute float phase;attribute float phaseSecondary;varying vec3 vColor;varying float opacity;uniform float time;uniform float step;float norm(float value, float min, float max ){return (value - min) / (max - min);}float lerp(float norm, float min, float max){return (max - min) * norm + min;}float map(float value, float sourceMin, float sourceMax, float destMin, float destMax){return lerp(norm(value, sourceMin, sourceMax), destMin, destMax);}void main() {float t = time* 0.0006;vColor = color;vec3 p = position;p.y = map(mod(phase+step, 1000.0), 0.0, 1000.0, 25.0, -8.0);p.x += sin(t+phase);p.z += sin(t+phaseSecondary);opacity = map(p.z, -150.0, 15.0, 0.0, 1.0);vec4 mvPosition = modelViewMatrix * vec4( p, 1.0 );gl_PointSize = size * ( 100.0 / -mvPosition.z );gl_Position = projectionMatrix * mvPosition;}`;const fragmentShader = `uniform sampler2D pointTexture;varying vec3 vColor;varying float opacity;void main() {gl_FragColor = vec4( vColor, opacity );gl_FragColor = gl_FragColor * texture2D( pointTexture, gl_PointCoord ); }`;function createSnowSet(sprite) {const totalPoints = 300;const shaderMaterial = new THREE.ShaderMaterial({uniforms: {...uniforms,pointTexture: {value: new THREE.TextureLoader().load(sprite)}},vertexShader,fragmentShader,blending: THREE.AdditiveBlending,depthTest: false,transparent: true,vertexColors: true});const geometry = new THREE.BufferGeometry();const positions = [];const colors = [];const sizes = [];const phases = [];const phaseSecondaries = [];const color = new THREE.Color();for (let i = 0; i < totalPoints; i++) {const [x, y, z] = [rand(25, -25), 0, rand(15, -150)];positions.push(x);positions.push(y);positions.push(z);color.set(randChoise(["#f1d4d4", "#f1f6f9", "#eeeeee", "#f1f1e8"]));colors.push(color.r, color.g, color.b);phases.push(rand(1000));phaseSecondaries.push(rand(1000));sizes.push(rand(4, 2));}geometry.setAttribute("position",new THREE.Float32BufferAttribute(positions, 3));geometry.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3));geometry.setAttribute("size", new THREE.Float32BufferAttribute(sizes, 1));geometry.setAttribute("phase", new THREE.Float32BufferAttribute(phases, 1));geometry.setAttribute("phaseSecondary",new THREE.Float32BufferAttribute(phaseSecondaries, 1));const mesh = new THREE.Points(geometry, shaderMaterial);scene.add(mesh);}const sprites = ["https://assets.codepen.io/3685267/snowflake1.png","https://assets.codepen.io/3685267/snowflake2.png","https://assets.codepen.io/3685267/snowflake3.png","https://assets.codepen.io/3685267/snowflake4.png","https://assets.codepen.io/3685267/snowflake5.png"];sprites.forEach(sprite => {createSnowSet(sprite);});}function addPlane(scene, uniforms, totalPoints) {const vertexShader = `attribute float size;attribute vec3 customColor;varying vec3 vColor;void main() {vColor = customColor;vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );gl_PointSize = size * ( 300.0 / -mvPosition.z );gl_Position = projectionMatrix * mvPosition;}`;const fragmentShader = `uniform vec3 color;uniform sampler2D pointTexture;varying vec3 vColor;void main() {gl_FragColor = vec4( vColor, 1.0 );gl_FragColor = gl_FragColor * texture2D( pointTexture, gl_PointCoord );}`;const shaderMaterial = new THREE.ShaderMaterial({uniforms: {...uniforms,pointTexture: {value: new THREE.TextureLoader().load(`https://assets.codepen.io/3685267/spark1.png`)}},vertexShader,fragmentShader,blending: THREE.AdditiveBlending,depthTest: false,transparent: true,vertexColors: true});const geometry = new THREE.BufferGeometry();const positions = [];const colors = [];const sizes = [];const color = new THREE.Color();for (let i = 0; i < totalPoints; i++) {const [x, y, z] = [rand(-25, 25), 0, rand(-150, 15)];positions.push(x);positions.push(y);positions.push(z);color.set(randChoise(["#93abd3", "#f2f4c0", "#9ddfd3"]));colors.push(color.r, color.g, color.b);sizes.push(1);}geometry.setAttribute("position",new THREE.Float32BufferAttribute(positions, 3).setUsage(THREE.DynamicDrawUsage));geometry.setAttribute("customColor",new THREE.Float32BufferAttribute(colors, 3));geometry.setAttribute("size", new THREE.Float32BufferAttribute(sizes, 1));const plane = new THREE.Points(geometry, shaderMaterial);plane.position.y = -8;scene.add(plane);}function addListners(camera, renderer, composer) {document.addEventListener("keydown", e => {const {x,y,z} = camera.position;console.log(`camera.position.set(${x},${y},${z})`);const {x: a,y: b,z: c} = camera.rotation;console.log(`camera.rotation.set(${a},${b},${c})`);});window.addEventListener("resize",() => {const width = window.innerWidth;const height = window.innerHeight;camera.aspect = width / height;camera.updateProjectionMatrix();renderer.setSize(width,height);composer.setSize(width,heihgt);},false);}</script></body>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/241134.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

网络编程:多进程和多线程编程

1. 多进程编程 1.1 fork #include <sys/types.h> #include <unistd.h> // 调用失败返回 -1 设置 errno pid_t fork( void );子进程返回 0&#xff0c;父进程返回子进程 PID&#xff1b; 信号位图被清除&#xff08;父进程的信号处理函数不再对新进程起作用&…

【网络编程】网络通信基础——简述TCP/IP协议

个人主页&#xff1a;兜里有颗棉花糖 欢迎 点赞&#x1f44d; 收藏✨ 留言✉ 加关注&#x1f493;本文由 兜里有颗棉花糖 原创 收录于专栏【网络编程】【Java系列】 本专栏旨在分享学习网络编程的一点学习心得&#xff0c;欢迎大家在评论区交流讨论&#x1f48c; 目录 一、ip地…

sql_lab之sqli中的报错注入,less13

报错注入&#xff08;less-13&#xff09; 正常报错注入&#xff1a; 1.输入用户名和密码123 123显示登录错误 2.输入用户名和密码123’ 123显示登录错误 123后面有’)说明是’)注入 3.查询数据库名 1) and updatexml(<a><b></b></a>,concat(1111…

大数据知识图谱解码:从核心概念到技术实战

文章目录 大数据知识图谱解码&#xff1a;从核心概念到技术实战1. 概述什么是知识图谱知识图谱与自然语言处理的关系 2. 发展历程语义网络本体论大数据时代的知识图谱知识图谱与深度学习的融合 3. 研究内容知识图谱的建模与表示知识抽取知识图谱的融合与对齐知识图谱的推理知识…

KMP入门级别算法详解--终于解决了(next数组详解)

对于正常的字符串模式匹配&#xff0c;主串长度为m&#xff0c;子串为n&#xff0c;时间复杂度会到达O&#xff08;m*n&#xff09;&#xff0c;而如果用KMP算法&#xff0c;复杂度将会减少线型时间O&#xff08;mn&#xff09;。 设主串为ptr"ababaaababaa";&#…

Prometheus介绍和安装

Prometheus介绍和安装 1. Prometheus介绍 Prometheus&#xff08;普罗米修斯&#xff09;是一个最初在SoundCloud上构建的监控系统。自2012年成为社区开源项目&#xff0c;拥有非常活跃的开发人员和用户社区。为强调开源及独立维护&#xff0c;Prometheus于2016年加入云原生云…

P4 音频知识点——PCM音频原始数据

目录 前言 01 PCM音频原始数据 1.1 频率 1.2 振幅&#xff1a; 1.3 比特率 1.4 采样 1.5 量化 1.6 编码 02. PCM数据有以下重要的参数&#xff1a; 采样率&#xff1a; 采集深度 通道数 ​​​​​​​ PCM比特率 ​​​​​​​ PCM文件大小计算&#xff1a; ​…

[THUPC 2024 初赛] 二进制 (树状数组单点删除+单点查询)(双堆模拟set)

题解 题目本身不难想 首先注意到所有查询的序列长度都是小于logn级别的 我们可以枚举序列长度len&#xff0c;然后用类似滑动窗口的方法&#xff0c;一次性预处理出每种字串的所有出现位置&#xff0c;也就是开N个set去维护所有的位置。预处理会进行O(logn)轮&#xff0c;每…

KubeSphere金丝雀发布流量分布调节不生效(将所有流量按比例分配给灰度发布版本)

如题 金丝雀发布按照流量比例访问不能生效 1、自制应用生成的路由添加注释: nginx.ingress.kubernetes.io/service-upstream:"true" 2、项目网关开启 3、完成 以上&#xff0c;祝好。

Tomcat远程调试

windows环境 写一个 startup-debug.bat&#xff0c;指定tomcat的根目录&#xff0c;端口自己定义 rem *******设置Tomcat目录*******-- set CATALINE_HOMED:\asd\A8-2\tomcat d: rem 8787为可用端口,为远程调试监听端口-- cd %CATALINE_HOME%/bin set JPDA_ADDRESS8787 set J…

Leetcode—445.两数相加II【中等】

2023每日刷题&#xff08;六十七&#xff09; Leetcode—445.两数相加II 实现代码 /*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2…

一个简单的 HTTP 请求和响应服务——httpbin

拉取镜像 docker pull kennethreitz/httpbin:latest 查看本地是否存在存在镜像 docker images | grep kennethreitz/httpbin:latest 创建 deployment&#xff0c;指定镜像 apiVersion: apps/v1 kind: Deployment metadata:labels:app: httpbinname: mm-httpbinnamespace: mm-…

Latex生成的PDF中加入书签/Navigation/导航

本文参考&#xff1a;【Latex学习】在生成pdf中加入书签/目录/提纲_latex 书签-CSDN博客 &#xff08;这篇文章写的真的太棒了&#xff01;非常推荐&#xff09; 题外话&#xff0c;我的碎碎念&#xff0c;这也是我如何提高搜索能力的办法&#xff1a;想在Latex生成的PDF中加入…

2023的AI工具集合,google和claude被禁用解决和edge的copilot

一、前言 AI工具集合 首先&#xff0c;OpenAI的ChatGPT以其深度学习模型和强大的语言处理能力引领了AI聊天机器人的潮流。自2022年11月30日上线以来&#xff0c;它创下了100万用户的注册记录&#xff0c;并被广泛应用于全球财富500强公司。为了实现盈利&#xff0c;OpenAI发布…

iOS 开发设计 App 上架符合要求的截图

1. 真机运行截屏 2. 可以在 Apple developer 官网 Design 下找到 iPhone 边框 https://developer.apple.com/design/resources/ 不用这个边框也行&#xff0c;可以参考已上架 App 的图片框 3. 使用 Procreate&#xff08;PhotoShop&#xff09;创建符合要求的画布大小 4. 导入…

springboot集成websocket全全全!!!

一、界面展示 二、前置了解 1.什么是websocket WebSocket是一种在单个TCP连接上进行全双工通信的持久化协议。 全双工协议就是客户端可以给我们服务器发数据 服务器也可以主动给客户端发数据。 2.为什么有了http协议 还要websocket 协议 http协议是一种无状态&#xff0c;非…

铭飞CMS cms/content/list接口存在SQL注入 附POC

@[toc] 铭飞CMS cms/content/list接口存在SQL注入 附POC 免责声明:请勿利用文章内的相关技术从事非法测试,由于传播、利用此文所提供的信息或者工具而造成的任何直接或者间接的后果及损失,均由使用者本人负责,所产生的一切不良后果与文章作者无关。该文章仅供学习用途使用…

内存函数的学习

额外知识点 第一个 假设c为int类型&#xff0c;&#xff08;char&#xff09;c之后&#xff0c;之后如果还用变量c的话&#xff0c;c依然为int类型。&#xff08;&#xff09;强制转换操作符并不会永久改变原本的变量类型。 第二个 \0在打印时不会显示出来 第三个 void …

增强客户获取能力:探索 B 端影片行销的影响

01 B端企业短视频营销的价值与难点 短视频营销在当今的市场中越来越受到重视。有数据显示&#xff0c;越来越多的市场人将尝试增加短视频营销的预算&#xff0c;并且在2023年&#xff0c;每5个市场人中就有1个人将尝试短视频营销。相较于内容深、信息量大的长视频&#xff0c;…

串口通信(7)-C#串口通信通信帮助类实例

本文讲解C#串口通信通信帮助类实例 首先创建winform项目添加界面和控件 UI界面 namespace SerialPortDemo {partial class MainForm{/// <summary>/// 必需的设计器变量。/// </summary>private System.ComponentModel.IContainer components = null;/// <sum…