confetti-cannon.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. (function(){
  2. window.HPX = window.HPX || {};
  3. window.HPX['confetti-cannon'] = function(el){
  4. const U = window.HPX._u;
  5. const k = U.canvas(el), ctx = k.ctx;
  6. const pal = U.palette(el);
  7. let parts = [];
  8. const fire = () => {
  9. for (let side=0; side<2; side++){
  10. const x0 = side===0 ? 20 : k.w-20;
  11. const y0 = k.h - 20;
  12. for (let i=0;i<40;i++){
  13. const a = side===0 ? U.rand(-Math.PI*0.7, -Math.PI*0.4) : U.rand(-Math.PI*0.6, -Math.PI*0.3) - Math.PI/2 - Math.PI/6;
  14. const spd = U.rand(300, 520);
  15. parts.push({
  16. x: x0, y: y0,
  17. vx: Math.cos(a)*spd, vy: Math.sin(a)*spd,
  18. w: U.rand(6,12), h: U.rand(3,7),
  19. rot: Math.random()*Math.PI, vr: U.rand(-6,6),
  20. c: pal[(Math.random()*pal.length)|0],
  21. life: 1
  22. });
  23. }
  24. }
  25. };
  26. fire();
  27. let last = 0;
  28. const stop = U.loop((t) => {
  29. ctx.clearRect(0,0,k.w,k.h);
  30. if (t - last > 3) { fire(); last = t; }
  31. const dt = 1/60;
  32. parts = parts.filter(p => p.life > 0 && p.y < k.h+40);
  33. for (const p of parts){
  34. p.vy += 520*dt;
  35. p.x += p.vx*dt; p.y += p.vy*dt;
  36. p.rot += p.vr*dt;
  37. p.life -= 0.006;
  38. ctx.save();
  39. ctx.translate(p.x, p.y); ctx.rotate(p.rot);
  40. ctx.globalAlpha = Math.max(0, p.life);
  41. ctx.fillStyle = p.c;
  42. ctx.fillRect(-p.w/2, -p.h/2, p.w, p.h);
  43. ctx.restore();
  44. }
  45. ctx.globalAlpha = 1;
  46. });
  47. return { stop(){ stop(); k.destroy(); } };
  48. };
  49. })();