用 Canvas 做一棵会旋转的粒子圣诞树(附完整源码)

浏览量 377

使用 Canvas 实现可旋转的粒子圣诞树。场景由深灰色代码编辑器背景、螺旋彩灯、飘雪和摆动挂件组成。

画面是怎么画出来的

页面用 Canvas 绘制。编辑器边框按窗口大小绘制,代码行持续向上滚动,再把这张底图和每一帧的雪花、树身粒子、彩灯及挂件合成。树灯按螺旋排列,每颗灯的闪烁相位各有不同,转起来能看出前后层次。

祝福语用 HTML 排版,留在画布前面。窗口变矮时,绘制逻辑会缩小树身,给底部两行文字留出位置。右上角可以暂停或继续播放。

完整源码

把下面的代码保存为 UTF-8 编码的 HTML 文件,用浏览器打开即可。网页可以离线运行。

编辑器里的代码和行号持续向上滚动,金绿色代码雨从上方落下。

<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>圣诞快乐 · Merry Christmas</title>
<style>
*{box-sizing:border-box}
body{margin:0;overflow:hidden;background:radial-gradient(ellipse at 50% 46%,#1c0b15 0%,#10080e 43%,#080609 85%);color:#fae5ae}
canvas{position:fixed;inset:0;width:100%;height:100%}
.greeting{color:#fff0dd;text-shadow:0 1px 10px #271a2a;position:absolute;bottom:max(clamp(12px,3vh,36px),env(safe-area-inset-bottom));left:0;width:100%;text-align:center;pointer-events:none}
h1{margin:0;font:italic 400 clamp(35px,8vmin,83px)/1.1 "Monotype Corsiva","Palatino Linotype",Georgia,serif;text-shadow:0 1px 13px #271a2a}
p{margin:.7em 0 0;padding-left:.45em;letter-spacing:.45em;font:inherit;font-size:clamp(14px,2.6vmin,23px);letter-spacing:.45em}
.dedication{margin:.5em 0 0;padding:0;letter-spacing:.08em;font:clamp(14px,2.7vmin,22px)/1.3 "Microsoft YaHei",sans-serif;color:#ffe2ed;text-shadow:0 1px 8px #271a2a}
.dedication-decoration{height:clamp(25px,4.7vmin,41px)}
@media(max-height:480px){.dedication-decoration{height:23px}h1{font-size:30px}.dedication{margin-top:.2em}}
button{position:fixed;top:max(12px,env(safe-area-inset-top));right:16px;padding:7px 12px;border:1px solid #45444f;border-radius:8px;background:#25252eee;color:#dedce4;font:12px/1.4 "Microsoft YaHei",sans-serif;cursor:pointer}
button:hover{background:#32313c;border-color:#686573}
button:focus-visible{outline:2px solid #d2afc4;outline-offset:3px}
</style>
</head>
<body>
<canvas aria-hidden="true"></canvas>
<main class="greeting"><h1>Merry Christmas</h1><p>圣诞快乐</p><div class="dedication-decoration" aria-hidden="true"></div><p class="dedication">DJY平安喜乐<br>Iloveyou~</p></main>
<button type="button">暂停动画</button>
<script>
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const button = document.querySelector('button');
const dedicationDecoration = document.querySelector('.dedication-decoration');
const random = Math.random;
const tau = Math.PI * 2;
const gold = ['#fff5ce','#ffda90','#e6a14f','#fff9e2'];
const ornaments = ['#ed7673','#78dcb9','#7caeff','#ffd584','#eaa3d6'];
let width, height, scale, center, treeTop, decorationY, time = 0, lastFrame, frame;

const scenery = document.createElement('canvas');
const landscape = scenery.getContext('2d');

const codeLines = [
  ['comment','// 圣诞树与飘雪'],
  ['accent','const snowflakes = Array.from({ length: 160 }, () => ({'],
  ['plain','  x: Math.random(),'],
  ['plain','  y: Math.random(),'],
  ['plain','  speed: 0.014 + Math.random() * 0.054'],
  ['accent','}));'],
  ['plain',''],
  ['accent','function drawSnow(time) {'],
  ['plain','  for (const flake of snowflakes) {'],
  ['plain','    const x = flake.x * width;'],
  ['plain','    const y = (flake.y + time * flake.speed) % 1;'],
  ['plain','    drawFlake(x, y * height);'],
  ['plain','  }'],
  ['accent','}'],
  ['plain',''],
  ['comment','// 一圈圈点亮圣诞树'],
  ['accent','function drawTree(time) {'],
  ['plain','  for (const light of garland) {'],
  ['plain','    const angle = light.angle + time * 0.37;'],
  ['plain','    const glow = 0.5 + 0.5 * Math.sin(time + light.phase);'],
  ['plain','    drawLight(light, angle, glow);'],
  ['plain','  }'],
  ['accent','}']
];
const codeInk = {comment:'#8c9a91',accent:'#a998b4',plain:'#aaa5ad'};

function drawCodeBackdrop(density) {
  scenery.width = canvas.width;
  scenery.height = canvas.height;
  landscape.setTransform(density,0,0,density,0,0);
  const barHeight = 24;
  const fontSize = Math.max(9,Math.min(13,width*.026));

  const railWidth = width < 520 ? 19 : 34;
  const codeLeft = railWidth + (width < 520 ? 26 : 38) + 11;

  landscape.save();
  landscape.fillStyle = '#17171f';
  landscape.fillRect(0,0,width,height);
  landscape.fillStyle = '#24242e';
  landscape.fillRect(0,0,width,barHeight);
  landscape.fillStyle = '#20202a';
  landscape.fillRect(0,barHeight,railWidth,height-barHeight);
  landscape.fillStyle = '#33323d';
  landscape.fillRect(railWidth-1,barHeight,1,height-barHeight);
  landscape.fillRect(codeLeft-8,barHeight,1,height-barHeight);
  landscape.fillRect(railWidth,barHeight-1,116,1);
  landscape.font = fontSize+'px "Cascadia Mono", Consolas, monospace';
  landscape.textBaseline = 'middle';
  landscape.fillStyle = '#c6b5bcaa';
  landscape.fillText('christmas.js',railWidth+10,barHeight/2);

  for (let i=0;i<4;i++) {
    const iconSize = width < 520 ? 5 : 7;
    landscape.strokeStyle = '#a9a8b467';
    landscape.strokeRect((railWidth-iconSize)/2,barHeight+12+i*18,iconSize,iconSize);
  }

  landscape.restore();
}

function resize() {
  width = innerWidth;
  height = innerHeight;
  const density = Math.min(devicePixelRatio || 1, 2);
  canvas.width = width * density;
  canvas.height = height * density;
  ctx.setTransform(density, 0, 0, density, 0, 0);
  center = width / 2;
  const greetingTop = document.querySelector('.greeting').getBoundingClientRect().top;
  treeTop = Math.min(height * .19, greetingTop * .24);
  scale = Math.max(1, Math.min(height * .54, width * 1.06, (greetingTop - treeTop - 9) / 1.10));
  decorationY = dedicationDecoration.getBoundingClientRect().top + 8;
  drawCodeBackdrop(density);
  draw();
}

function particle(garland) {
  const level = Math.pow(random(), garland ? 1 : .74);
  const angle = garland ? level * tau * 8.6 + (random() - .5) * .28 : random() * tau;
  const edge = garland ? 1 : (.35 + .65 * Math.sqrt(random())) * (.81 + .19 * Math.cos(level * tau * 9));
  const color = garland ? gold : random() < .16 ? ornaments : ['#41765b','#66976b','#93bb76','#b5a870'];
  return {level, angle, edge, color:color[Math.floor(random() * color.length)], size:.0008 + random() * (garland ? .0032 : .0024), phase:random()*tau, garland};
}
const particles = Array.from({length:3900}, (_, i) => particle(i < 1700));
const bulbColors = ['#ff456f','#54ff99','#44caff','#f97bff','#ffcf48','#ff7739'];
const bulbs = Array.from({length:138}, (_, i) => {
  const level = .12 + .86 * i / 137;
  return {
    level,
    angle: level * tau * 8.6 + .22,
    color: bulbColors[(i * 5 + Math.floor(i / 7)) % bulbColors.length],
    phase: random() * tau
  };
});
const snow = Array.from({length:160}, () => ({x:random(), y:random(), size:.55+random()*1.8, speed:.014+random()*.054, phase:random()*tau}));
const rays = Array.from({length:14}, (_, i) => ({angle:i*tau/14 + random()*.3, length:.11+random()*.27, width:.01+random()*.03}));

function dot(x,y,r,color,opacity) {
  ctx.globalAlpha = opacity;
  ctx.fillStyle = color;
  ctx.beginPath();
  ctx.arc(x,y,r,0,tau);
  ctx.fill();
}

function star() {
  ctx.save();
  ctx.translate(center,treeTop);
  const glow = ctx.createRadialGradient(0,0,0,0,0,scale*.15);
  glow.addColorStop(0,'#fffce9');
  glow.addColorStop(.066,'#ffd178cf');
  glow.addColorStop(.3,'#f6aa4620');
  glow.addColorStop(1,'#f6aa4600');
  ctx.globalAlpha = .88 + .1*Math.sin(time*2.1);
  ctx.fillStyle = glow;
  ctx.fillRect(-scale*.15,-scale*.15,scale*.30,scale*.30);
  for (const ray of rays) {
    ctx.save();
    ctx.rotate(ray.angle + .04*Math.sin(time*.55));
    const length = ray.length*scale*.76;
    const beam = ctx.createLinearGradient(0,0,length,0);
    beam.addColorStop(0,'#fff1c7');
    beam.addColorStop(.22,'#ffc97746');
    beam.addColorStop(1,'#ffc97700');
    ctx.fillStyle = beam;
    ctx.beginPath();
    ctx.moveTo(0,0);
    ctx.quadraticCurveTo(length*.44,-scale*ray.width,length,0);
    ctx.quadraticCurveTo(length*.42,scale*ray.width,0,0);
    ctx.fill();
    ctx.restore();
  }
  dot(0,0,Math.max(2.5,scale*.010),'#fffdf1',1);
  ctx.restore();
}

function kittyOrnament(x, y, size) {

  ctx.save();
  ctx.globalAlpha = 1;
  ctx.translate(x,y);
  ctx.rotate(.075 * Math.sin(time*1.7));
  ctx.scale(size,size);
  ctx.lineWidth = .045;
  ctx.strokeStyle = '#ffdb8d';
  ctx.beginPath();
  ctx.moveTo(0,-.43);
  ctx.lineTo(0,-.79);
  ctx.stroke();

  ctx.fillStyle = '#fff3ed';
  ctx.strokeStyle = '#814659';
  ctx.beginPath();
  ctx.moveTo(-.47,-.15);
  ctx.quadraticCurveTo(-.55,-.59,-.36,-.56);
  ctx.lineTo(-.15,-.41);
  ctx.quadraticCurveTo(0,-.45,.17,-.41);
  ctx.lineTo(.36,-.56);
  ctx.quadraticCurveTo(.55,-.59,.47,-.15);
  ctx.bezierCurveTo(.67,.24,.37,.43,0,.43);
  ctx.bezierCurveTo(-.37,.43,-.67,.24,-.47,-.15);
  ctx.fill();
  ctx.stroke();

  for (const side of [-1,1]) {
    ctx.fillStyle = '#402a33';
    ctx.beginPath();
    ctx.ellipse(.19*side,.08,.04,.061,0,0,tau);
    ctx.fill();
    ctx.lineWidth = .025;
    ctx.strokeStyle = '#814659';
    for (let i=0;i<3;i++) {
      ctx.beginPath();
      ctx.moveTo(.41*side,.08+i*.075);
      ctx.lineTo(.59*side,.055+i*.10);
      ctx.stroke();
    }
  }
  ctx.fillStyle = '#f4bd50';
  ctx.beginPath();
  ctx.ellipse(0,.16,.062,.041,0,0,tau);
  ctx.fill();

  ctx.fillStyle = '#fa679b';
  ctx.beginPath();
  ctx.moveTo(.31,-.34);
  ctx.bezierCurveTo(-.02,-.68,-.01,-.13,.31,-.29);
  ctx.bezierCurveTo(.64,-.13,.65,-.68,.31,-.34);
  ctx.fill();
  ctx.stroke();
  dot(.31,-.33,.081,'#ffb4cf',1);
  ctx.restore();
}

function mollyOrnament(x,y,size) {
  ctx.save();
  ctx.translate(x,y);
  ctx.rotate(.09*Math.sin(time*1.6+1));
  ctx.scale(size,size);
  ctx.globalAlpha = 1;
  ctx.lineWidth = .047;
  ctx.strokeStyle = '#f7c875';
  ctx.beginPath();
  ctx.moveTo(0,-.84);
  ctx.lineTo(0,-.48);
  ctx.stroke();
  dot(0,.02,.54,'#e9e3fc',1);
  dot(0,.01,.46,'#a79ad6',1);
  dot(0,.06,.397,'#ffe0c2',1);
  ctx.fillStyle = '#f1bf62';
  ctx.beginPath();
  ctx.moveTo(-.39,.02);
  ctx.quadraticCurveTo(-.42,-.37,0,-.35);
  ctx.quadraticCurveTo(.35,-.36,.39,.03);
  ctx.quadraticCurveTo(.18,-.04,.10,-.18);
  ctx.quadraticCurveTo(.02,-.04,-.12,-.03);
  ctx.lineTo(-.09,-.16);
  ctx.quadraticCurveTo(-.19,-.03,-.39,.02);
  ctx.fill();
  for (const side of [-1,1]) {
    dot(side*.162,.109,.086,'#fff',1);
    dot(side*.162,.118,.059,'#47a89c',1);
    dot(side*.162,.114,.030,'#184451',1);
    dot(side*.162-.013,.096,.014,'#fff',1);
    dot(side*.247,.229,.047,'#f49397',.67);
  }
  ctx.strokeStyle = '#d76a78';
  ctx.lineWidth = .046;
  ctx.lineCap = 'round';
  ctx.beginPath();
  ctx.moveTo(-.065,.253);
  ctx.quadraticCurveTo(0,.20,.065,.253);
  ctx.stroke();
  ctx.restore();
}

function giftOrnament(x,y,size,color) {
  ctx.save();
  ctx.translate(x,y);
  ctx.rotate(.14*Math.sin(time*1.9+x));
  ctx.scale(size,size);
  ctx.globalAlpha = 1;
  ctx.strokeStyle = '#ffe2a0';
  ctx.lineWidth = .042;
  ctx.beginPath();
  ctx.moveTo(0,-.83);
  ctx.lineTo(0,-.33);
  ctx.bezierCurveTo(-.48,-.61,-.45,-.16,0,-.33);
  ctx.bezierCurveTo(.45,-.16,.48,-.61,0,-.33);
  ctx.stroke();
  ctx.fillStyle = color;
  ctx.fillRect(-.36,-.29,.72,.62);
  ctx.fillRect(-.41,-.31,.82,.16);
  ctx.fillStyle = '#ffe5a6';
  ctx.fillRect(-.055,-.31,.11,.64);
  ctx.fillRect(-.36,.01,.72,.08);
  ctx.restore();
}

function drawDedicationDecoration() {
  const span = Math.min(width*.56,250);
  ctx.globalAlpha = .65;
  ctx.strokeStyle = '#dfb77a';
  ctx.lineWidth = 1;
  ctx.beginPath();
  ctx.moveTo(center-span/2,decorationY);
  ctx.quadraticCurveTo(center,decorationY+14,center+span/2,decorationY);
  ctx.stroke();
  for (let i=0;i<12;i++) {
    const t = (i+.5)/12;
    const x = center + (t-.5)*span;
    const y = decorationY + 28*t*(1-t);
    const color = bulbColors[i%bulbColors.length];
    const brightness = .76 + .24*Math.sin(time*2.4+i);
    dot(x,y,6,color,brightness*.22);
    dot(x,y,2.4,color,brightness);
    dot(x,y,.85,'#fff8df',brightness);
  }
  kittyOrnament(center,decorationY+16,Math.min(23,span*.095));
}

function drawCodeRain(context, w, h, seconds) {
  const spacing = w < 600 ? 24 : 30;
  const row = 15;
  context.save();
  context.font = '12px Consolas, monospace';
  context.textBaseline = 'top';
  for (let col = 0; col * spacing < w; col++) {
    const speed = 28 + (col * 37 % 66);
    const distance = (seconds * speed + col * 137) % (h + 210);
    const head = Math.floor(distance / row) * row;
    const x = col * spacing + 5;
    for (let tail = 0; tail < 12; tail++) {
      const y = head - tail * row;
      if (y < 0 || y >= h) continue;
      const code = (col * 19 + Math.floor((y - seconds * speed) / row) * 13) >>> 0;
      const alpha = (1 - tail / 12) ** 2 * (tail === 0 ? .62 : .32);
      context.fillStyle = tail === 0 ? '#ffdc91' : '#4bc99b';
      context.globalAlpha = alpha;
      context.fillText(['0', '1', '1', '0', '+', '·', '0'][code % 7], x, y);
    }
  }
  context.restore();
}
 
function drawScrollingCode() {
  const top = 24;
  const rail = width < 520 ? 19 : 34;
  const codeLeft = rail + (width < 520 ? 26 : 38) + 11;
  const fontSize = Math.max(9, Math.min(13, width * .026));
  const lineHeight = fontSize * 1.54;
  const scroll = time * 19;
  const first = Math.floor(scroll / lineHeight);
  const offset = scroll % lineHeight;
  ctx.save();
  ctx.beginPath();
  ctx.rect(rail, top, width - rail, height - top);
  ctx.clip();
  ctx.font = fontSize + 'px "Cascadia Mono", Consolas, monospace';
  ctx.textBaseline = 'middle';
  for (let row = 0; row <= Math.ceil((height - top) / lineHeight); row++) {
    const y = top + (row + .8) * lineHeight - offset;
    const index = first + row;
    const [tone, line] = codeLines[index % codeLines.length];
    ctx.globalAlpha = y > height * .74 ? .31 : .52;
    ctx.fillStyle = '#777784';
    ctx.fillText(String(index + 1).padStart(2, '0'), rail + 7, y);
    ctx.fillStyle = codeInk[tone];
    ctx.fillText(line, codeLeft, y);
  }
  ctx.restore();
}

function draw() {
  ctx.drawImage(scenery,0,0,width,height);
  drawScrollingCode();
  drawCodeRain(ctx, width, height, time);
  for (const flake of snow) {
    const x = flake.x*width + 18*Math.sin(time*.65+flake.phase);
    const y = (flake.y+time*flake.speed)%1*height;
    dot(x,y,flake.size,'#fff8e5',.13+flake.size*.19);
  }
  const points = particles.map(p => {
    const angle = p.angle + time*.37;
    const radius = (.012 + .419*p.level)*p.edge;
    const depth = Math.sin(angle);
    return {p, depth, x:center+Math.cos(angle)*radius*scale, y:treeTop+(p.level + depth*radius*.21)*scale};
  }).sort((a,b) => a.depth-b.depth);
  ctx.globalCompositeOperation = 'lighter';
  for (const {p, depth, x, y} of points) {
    const pulse = .5+.5*Math.sin(time*3+p.phase);
    const alpha = (p.garland ? .46 : .23) + pulse*.39 + depth*.10;
    const radius = Math.max(.43,p.size*scale);
    if (p.garland && pulse>.9 && radius>1) dot(x,y,radius*1.9,p.color,alpha*.08);
    dot(x,y,radius*(p.garland ? 1.12 : 1),p.color,alpha);
  }
  for (const bulb of bulbs) {
    const angle = bulb.angle + time * .37;
    const depth = Math.sin(angle);
    const radius = .012 + .419 * bulb.level;
    const x = center + Math.cos(angle) * radius * scale;
    const y = treeTop + (bulb.level + depth * radius * .21) * scale;
    const pulse = .64 + .36 * Math.sin(time * 2.4 + bulb.phase);
    const brightness = pulse * (.67 + .27 * depth);
    const size = Math.max(1.35, scale * (.0037 + .0011 * depth));
    dot(x,y,size * 2.05,bulb.color,brightness * .13);
    dot(x,y,size*1.24,bulb.color,.60 + brightness * .38);
    dot(x,y,size * .43,'#fff4e3',brightness * .85);
  }
  ctx.globalCompositeOperation = 'source-over';
  const ornamentSize = Math.max(18,scale*.074);
  giftOrnament(center+scale*.079,treeTop+scale*.39,ornamentSize*.8,'#ee799e');
  mollyOrnament(center-scale*.16,treeTop+scale*.56,ornamentSize);
  giftOrnament(center-scale*.078,treeTop+scale*.85,ornamentSize,'#53bba5');
  kittyOrnament(center + scale*.155,treeTop + scale*.66,Math.max(19,scale*.073));
  star();
  drawDedicationDecoration();
  ctx.globalAlpha = 1;
}

function animate(now) {
  if (lastFrame !== undefined) time += Math.min((now-lastFrame)/1000,.05);
  lastFrame = now;
  draw();
  frame = requestAnimationFrame(animate);
}

button.addEventListener('click', () => {
  if (frame !== undefined) {
    cancelAnimationFrame(frame);
    frame = undefined;
    button.textContent = '播放动画';
  } else {
    lastFrame = undefined;
    frame = requestAnimationFrame(animate);
    button.textContent = '暂停动画';
  }
});

addEventListener('resize', resize);
resize();
if (matchMedia('(prefers-reduced-motion: reduce)').matches) {
  button.textContent = '播放动画';
} else {
  frame = requestAnimationFrame(animate);
}
</script>
</body>
</html>







发表评论
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇
☁ 场景与音乐
场景音乐
原创场景配乐,点击播放。