1.python圣诞树
废话不多说。上代码
import turtle as t # as就是取个别名,后续调用的t都是turtle
from turtle import *
import random as r
import time
n = 100.0
speed("fastest") # 定义速度
screensize(bg='black') # 定义背景颜色,可以自己换颜色
left(90)
forward(3 * n)
color("orange", "yellow") # 定义最上端星星的颜色,外圈是orange,内部是yellow
begin_fill()
left(126)
for i in range(5): # 画五角星
forward(n / 5)
right(144) # 五角星的角度
forward(n / 5)
left(72) # 继续换角度
end_fill()
right(126)
def drawlight(): # 定义画彩灯的方法
if r.randint(0, 30) == 0: # 如果觉得彩灯太多,可以把取值范围加大一些,对应的灯就会少一些
color('tomato') # 定义第一种颜色
circle(6) # 定义彩灯大小
elif r.randint(0, 30) == 1:
color('orange') # 定义第二种颜色
circle(3) # 定义彩灯大小
else:
color('dark green') # 其余的随机数情况下画空的树枝
color("dark green") # 定义树枝的颜色
backward(n * 4.8)
def tree(d, s): # 开始画树
if d <= 0: return
forward(s)
tree(d - 1, s * .8)
right(120)
tree(d - 3, s * .5)
drawlight() # 同时调用小彩灯的方法
right(120)
tree(d - 3, s * .5)
right(120)
backward(s)
tree(15, n)
backward(n / 2)
for i in range(200): # 循环画最底端的小装饰
a = 200 - 400 * r.random()
b = 10 - 20 * r.random()
up()
forward(b)
left(90)
forward(a)
down()
if r.randint(0, 1) == 0:
color('tomato')
else:
color('wheat')
circle(2)
up()
backward(a)
right(90)
backward(b)
t.color("dark red", "red") # 定义字体颜色
t.write("Merry Christmas", align="center", font=("Comic Sans MS", 40, "bold")) # 定义文字、位置、字体、大小
def drawsnow(): # 定义画雪花的方法
t.ht() # 隐藏笔头,ht=hideturtle
t.pensize(2) # 定义笔头大小
for i in range(200): # 画多少雪花
t.pencolor("white") # 定义画笔颜色为白色,其实就是雪花为白色
t.pu() # 提笔,pu=penup
t.setx(r.randint(-350, 350)) # 定义x坐标,随机从-350到350之间选择
t.sety(r.randint(-100, 350)) # 定义y坐标,注意雪花一般在地上不会落下,所以不会从太小的纵座轴开始
t.pd() # 落笔,pd=pendown
dens = 6 # 雪花瓣数设为6
snowsize = r.randint(1, 10) # 定义雪花大小
for j in range(dens): # 就是6,那就是画5次,也就是一个雪花五角星
# t.forward(int(snowsize)) #int()取整数
t.fd(int(snowsize))
t.backward(int(snowsize))
# t.bd(int(snowsize)) #注意没有bd=backward,但有fd=forward,小bug
t.right(int(360 / dens)) # 转动角度
drawsnow() # 调用画雪花的方法
t.done() # 完成,否则会直接关闭
2.html5圣诞树1
2.1 index.html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="A Christmas tree built out of form elements." />
<meta name="author" content="Hakim El Hattab" />
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<title>DOM Tree</title>
<link href="css/domtree.css" rel="stylesheet" media="screen" />
<link href='https://fonts.googleapis.com/css?family=Armata' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="tree"></div>
<script src="js/domtree.js"></script>
<!-- Third party scripts and sharing UI -->
<p class="project-title">DOM Tree</p>
<div class="credits">
<a href="https://github.com/hakimel/dom-tree">Source on GitHub</a>
<a href="https://twitter.com/share?text=A%20Christmas%20tree%20made%20out%20of%20form%20elements&url=http://lab.hakim.se/domtree&via=hakimel&related=hakimel" target="_blank">Tweet this</a>
<a href="https://twitter.com/hakimel">Follow @hakimel</a>
</div>
<style type="text/css" media="screen">
.project-title {
position: absolute;
left: 25px;
bottom: 20px;
font-size: 16px;
color: #fff;
}
.credits {
position: absolute;
right: 20px;
bottom: 25px;
font-size: 15px;
z-index: 20;
color: #fff;
vertical-align: middle;
}
.credits * + * {
margin-left: 15px;
}
.credits a {
padding: 8px 10px;
color: rgba(255,255,255,0.7);
border: 2px solid rgba(255,255,255,0.7);
text-decoration: none;
}
.credits a:hover {
border-color: #fff;
color: #fff;
}
@media screen and (max-width: 1040px) {
.project-title {
display: none;
}
.credits {
width: 100%;
left: 0;
right: auto;
bottom: 0;
padding: 30px 0;
background: #b72424;
text-align: center;
}
.credits a {
display: inline-block;
margin-top: 7px;
margin-bottom: 7px;
}
}
</style>
<script>
var _gaq = [['_setAccount', 'UA-15240703-1'], ['_trackPageview']];
(function(d, t) {
var g = d.createElement(t),
s = d.getElementsByTagName(t)[0];
g.async = true;
g.src = ('https:' == location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
s.parentNode.insertBefore(g, s);
})(document, 'script');
</script>
</body>
</html>
2.2 domtree.css代码
/*********************************************
* RESET
*********************************************/
html{color:#000;background:#222222;}
a{cursor:pointer;}
html,body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0;}
table{border-collapse:collapse;border-spacing:0;}
fieldset,img{border:0;}
address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}
li{list-style:none;}
caption,th{text-align:left;}
/* h1,h2,h3,h4,h5,h6{font-size:100%;} */
q:before,q:after{content:'';}
abbr,acronym {border:0;font-variant:normal;}
sup {vertical-align:text-top;}
sub {vertical-align:text-bottom;}
input,textarea,select{font-family:inherit;font-size:inherit;font-weight:inherit;outline-style:none;outline-width:0pt;}
legend{color:#000;}
a:focus,object,h1,h2,h3,h4,h5,h6{-moz-outline-style: none; border:0px;}
/*input[type="Submit"]{cursor:pointer;}*/
strong {font-weight: bold;}
/*********************************************
* GLOBAL
*********************************************/
body, html {
overflow: hidden;
font-family: Helvetica, Arial, sans-serif;
color: #fff;
font-size: 11px;
width: 100%;
height: 100%;
background: #b72424;
background: -moz-radial-gradient(center, ellipse cover, #b72424 0%, #492727 100%);
background: -webkit-gradient(radial, center center, 0px, center center, 100%, color-stop(0%,#b72424), color-stop(100%,#492727));
background: -webkit-radial-gradient(center, ellipse cover, #b72424 0%,#492727 100%);
background: radial-gradient(center, ellipse cover, #b72424 0%,#492727 100%);
}
@keyframes spin {
0% { transform: rotateY( 0deg ); }
100% { transform: rotateY( 360deg ); }
}
body {
perspective: 3000px;
perspective-origin: 0 20%;
}
.tree {
margin: 0 auto;
position: relative;
animation: spin 18s infinite linear;
transform-origin: 50% 0;
transform-style: preserve-3d;
}
.tree * {
position: absolute;
transform-origin: 0 0;
}
2.3 domtree.js代码
const width = 500;
const height = 600;
const quantity = 150;
const types = [ 'text', 'select', 'progress', 'meter', 'button', 'radio', 'checkbox' ];
const greetings = [ 'Joyeuses Fêtes','Felices Fiestas','God Jul','Boas Festas','Mutlu Bayramlar','Sarbatori Fericite','Jie Ri Yu Kuai','Bones Festes','Tanoshii kurisumasu wo','Buone Feste','Happy Holidays', 'Ii holide eximnandi','Frohe Feiertage','Prettige feestdagen','Beannachtaí na Féile','Vesele Praznike','Selamat Hari Raya','Sretni praznici' ];
let tree = document.querySelector( '.tree' ),
treeRotation = 0;
tree.style.width = width + 'px';
tree.style.height = height + 'px';
window.addEventListener( 'resize', resize, false );
// The tree
for( var i = 0; i < quantity; i++ ) {
let element = null,
type = types[ Math.floor( Math.random() * types.length ) ],
greeting = greetings[ Math.floor( Math.random() * greetings.length ) ];
let x = width/2,
y = Math.round( Math.random() * height );
let rx = 0,
ry = Math.random() * 360,
rz = -Math.random() * 15;
let elemenWidth = 5 + ( ( y / height ) * width / 2 ),
elemenHeight = 26;
switch( type ) {
case 'button':
element = document.createElement( 'button' );
element.textContent = greeting;
element.style.width = elemenWidth + 'px';
element.style.height = elemenHeight + 'px';
break;
case 'progress':
element = document.createElement( 'progress' );
element.style.width = elemenWidth + 'px';
element.style.height = elemenHeight + 'px';
if( Math.random() > 0.5 ) {
element.setAttribute( 'max', '100' );
element.setAttribute( 'value', Math.round( Math.random() * 100 ) );
}
break;
case 'select':
element = document.createElement( 'select' );
element.setAttribute( 'selected', greeting );
element.innerHTML = '<option>' + greetings.join( '</option><option>' ) + '</option>';
element.style.width = elemenWidth + 'px';
element.style.height = elemenHeight + 'px';
break;
case 'meter':
element = document.createElement( 'meter' );
element.setAttribute( 'min', '0' );
element.setAttribute( 'max', '100' );
element.setAttribute( 'value', Math.round( Math.random() * 100 ) );
element.style.width = elemenWidth + 'px';
element.style.height = elemenHeight + 'px';
break;
case 'text':
default:
element = document.createElement( 'input' );
element.setAttribute( 'type', 'text' );
element.setAttribute( 'value', greeting );
element.style.width = elemenWidth + 'px';
element.style.height = elemenHeight + 'px';
}
element.style.transform = `translate3d(${x}px, ${y}px, 0px) rotateX(${rx}deg) rotateY(${ry}deg) rotateZ(${rz}deg)`;
tree.appendChild( element );
}
// Let it snow
for( var i = 0; i < 200; i++ ) {
let element = document.createElement( 'input' );
element.setAttribute( 'type', 'radio' );
let spread = window.innerWidth/2;
let x = Math.round( Math.random() * spread ) - ( spread / 4 ),
y = Math.round( Math.random() * height ),
z = Math.round( Math.random() * spread ) - ( spread / 2 );
let rx = 0,
ry = Math.random() * 360,
rz = 0;
if( Math.random() > 0.5 ) element.setAttribute( 'checked', '' );
element.style.transform = `translate3d(${x}px, ${y}px, ${z}px) rotateX(${rx}deg) rotateY(${ry}deg) rotateZ(${rz}deg)`;
tree.appendChild( element );
}
function resize() {
tree.style.top = ( ( window.innerHeight - height - 100 ) / 2 ) + 'px';
}
resize();
3.html5圣诞树2(可选择音乐)
<!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>
以上代码大家经供参考。大家可以学习!