3D煙花是一種非常炫酷的效果,可以讓你的網頁內容更具吸引力。
以下是一個基于HTML代碼實現3D煙花效果的范例:
<!DOCTYPE html> <html> <head> <title>3D煙花效果</title> <style> canvas { background-color: #000; position: absolute; z-index: -1; } </style> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script src="https://threejs.org/build/three.min.js"></script> <script> var container; var camera, scene, renderer; var points, pointGeo, pointMat; var controls; init(); animate(); function init() { container = document.createElement( 'div' ); document.body.appendChild( container ); camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 1000 ); camera.position.z = 100; scene = new THREE.Scene(); pointGeo = new THREE.BufferGeometry(); pointMat = new THREE.PointsMaterial( { color: 0xffffff, size: 0.5 } ); points = new THREE.Points( pointGeo, pointMat ); scene.add( points ); renderer = new THREE.WebGLRenderer( { alpha: true } ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); container.appendChild( renderer.domElement ); controls = new THREE.OrbitControls( camera, renderer.domElement ); controls.enableZoom = false; controls.enablePan = false; controls.minDistance = 60; controls.maxDistance = 150; window.addEventListener( 'resize', onWindowResize, false ); document.addEventListener( 'mousemove', onDocumentMouseMove, false ); } function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth, window.innerHeight ); } function onDocumentMouseMove( event ) { pointMat.color.setHSL( Math.random(), 1, 0.5 ); } function animate() { requestAnimationFrame( animate ); render(); } function render() { var attributes = pointGeo.attributes; for ( var i = 0; i< attributes.size.array.length; i++ ) { if ( i >= 3 ) { attributes.size.array[ i ] = 0; } } attributes.size.needsUpdate = true; renderer.render( scene, camera ); } </script> </head> <body> </body> </html>
這段代碼使用了Three.js庫和OrbitControls.js庫。
在HTML中,我們為畫布(canvas)設置了背景色和位置,并添加了jQuery和Three.js庫的鏈接代碼。
在JavaScript中,我們使用了代碼來初始化相機、場景、渲染器以及點集對象的材料,同時也創建了相關的視角控制器。
最后,我們使用JavaScript動畫函數requestAnimationFrame()和jQuery事件監聽函數來完成3D煙花效果。