首页 > 其他分享 >HTML实现圣诞树

HTML实现圣诞树

时间:2024-01-02 11:32:47浏览次数:29  
标签:const 实现 float THREE geometry color HTML 圣诞树 new


Code:

<!DOCTYPE HEML PUBLIC>

<html xmlns="http://www.w3.org/1999/html">

<head>

    <meta charset="utf-8">

    <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>

</head>

<body>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/postprocessing/EffectComposer.js"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/postprocessing/RenderPass.js"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/postprocessing/ShaderPass.js"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/shaders/CopyShader.js"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/shaders/LuminosityHighPassShader.js"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/postprocessing/UnrealBloomPass.js"></script>

<div id="overlay">

    <ul>

        <li class="title">Select Music</li>

        <li>

            <button class="btn" id="btnA" type="button">

                Snowflakes Falling Down by Simon Panrucker

            </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">OR</li>

        <li>

            <input type="file" id="upload" hidden/>

            <label for="upload">Upload File</label>

        </li>

    </ul>

</div>

</body>

<script>

    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">Please Wait...</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">Please Wait...</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, height);

            },

            false
        );

    }


</script>

</html>


标签:const,实现,float,THREE,geometry,color,HTML,圣诞树,new
From: https://blog.51cto.com/aiyc/9065933

相关文章

  • 【JDK源码】Java中LinkedList的实现
    JDK版本:1.8.0_271基础介绍LinkedList底层数据结构是一个双向链表:链表的每个节点叫做Node,在Node中,prev属性表示前一个节点的位置,next属性表示后一个节点的位置first是双向链表的头节点,它的前一个节点是nulllast是双向链表的尾节点,它的后一个节点是null当链表中没有数据时,fi......
  • 【JDK源码】ArrayList的代码实现
    JDK版本:1.8.0_271基础介绍ArrayList底层数据结构就是一个数组:index表示数组下标,从0开始计数,elementDatda表示数组本身DEFAULT_CAPACITY表示数组的初始化大小,默认是10size表示数组的大小,int类型,没有使用volatile修饰,非线程安全modCount统计当前数组被修改的版本次数,数......
  • JDK9中的String底层实现为什么用UTF-16而不用UTF-8呢?
    UTF-8是一种对空间利用效率最高的编码集,它是不定长的,使用1~4字节为每个字符编码。这种情况下,如果能用一个字节存放字符就不会使用两个字节,两个字节不够就用三个字节。这种编码集只适用于传输和存储,并不适合拿来做String的底层实现。String有随机访问的方法,比如charAt、subString等......
  • 如何用 100 行 Shell 脚本实现一个 Docker?
    本文主要介绍使用shell实现一个简易的Docker。一、目的在初接触Docker的时候,我们必须要了解的几个概念就是Cgroup、Namespace、RootFs,如果本身对虚拟化的发展没有深入的了解,那么很难对这几个概念有深入的理解。本文的目的就是通过在操作系统中以交互式的方式去理解,Cgroup/Namesp......
  • 新玩法!如何在 PieCloudDB Database 中“种”一棵圣诞树?
    随着圣诞节的到来,很多城市也都张灯结彩,处处充满了节日气息。圣诞节当然离不开圣诞树啦!和家人一起挂上圣诞装饰,树下放上互相准备的小礼物,小小的仪式感,充满了浪漫与温馨。今天,我们将教你在PieCloudDBDatabase中“种”下今年的圣诞树!就像种树前需要松土、挖种植坑,在拥有一棵圣诞树......
  • TiDB是如何在国有大银行实现数据库业务“一换三”的
    作者:TiDBer_小黑羊最近,看到一个国有大银行的数据库案例,狠狠刷新了我的认知↓三个“国外顶流数据库”没搞定的系统,竟然被一家国产数据库厂商拿下了。可以说,这一次,国产数据库不仅打了翻身仗,还攀上了一个前所未有的高峰。这事儿有多“离谱”?听我给你捋捋↓一、500TB数据,让三大顶流......
  • 【揭秘】如何使用LinkedHashMap来实现一个LUR缓存?
    LRU(LeastRecentlyUsed)缓存是一种常用的缓存淘汰策略,用于在有限的缓存空间中存储数据。其基本思想是:如果数据最近被访问过,那么在未来它被访问的概率也更高。因此,LRU缓存会保留最近访问过的数据,并在缓存满时淘汰最久未使用的数据定义LRU(LeastRecentlyUsed)缓存是一种常用的......
  • Landsat 7大气校正法的地表温度反演:ENVI实现
    本文介绍基于ENVI软件,实现对Landsat7遥感影像加以大气校正方法的地表温度反演操作。(基于ENVI的Landsat7地表温度(LST)大气校正方法反演与地物温度分析)1图像前期处理与本文理论部分更新:基于GEE的地表温度Landsat反演可以看谷歌地球引擎GEE批量计算Landsat地表温度,自动批量操作......
  • 【Java技术专题】「入门到精通系列」深入探索Java技术中常用到的六种加密技术和实现
    背景介绍重点记住现代密码学的柯克霍夫原则:数据安全取决于密钥而不是算法的保密。即使密码系统的细节已经公开,只要密钥保密,系统依然可以保持安全。本文介绍了6种常用的加密技术和相应的代码实现。柯克霍夫原则柯克霍夫原则(Kerckhoffs'sprinciple)是密码学中的一个重要原则,提出者为......
  • Bellman-Ford算法实现带有负权边的单源最短路
    Bellman-Ford算法对于Dijkstra算法,不妨给出这样一个例子graphLRA((A))-->|1|C((C))A-->|2|D((D))D-->|-4|C根据Dijkstra算法的流程,选取A为源点。更新与A邻接的顶点,有C和D。选取已更新顶点中距离A的最小值,显然选择边权为1的边所连接的顶点C,并将C收入最短路集合S中,此......