matrix-rain.js 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. (function(){
  2. window.HPX = window.HPX || {};
  3. window.HPX['matrix-rain'] = function(el){
  4. const U = window.HPX._u;
  5. const k = U.canvas(el), ctx = k.ctx;
  6. const glyphs = 'アイウエオカキクケコサシスセソタチツテトナニヌネノ0123456789ABCDEF'.split('');
  7. const fs = 16;
  8. let cols = 0, drops = [];
  9. const init = () => {
  10. cols = Math.ceil(k.w/fs);
  11. drops = Array.from({length:cols}, () => U.rand(-20, 0));
  12. };
  13. init();
  14. let lw = k.w, lh = k.h;
  15. const stop = U.loop(() => {
  16. if (k.w!==lw || k.h!==lh){ init(); lw=k.w; lh=k.h; }
  17. ctx.fillStyle = 'rgba(0,0,0,0.08)';
  18. ctx.fillRect(0,0,k.w,k.h);
  19. ctx.font = fs+'px monospace';
  20. for (let i=0;i<cols;i++){
  21. const ch = glyphs[(Math.random()*glyphs.length)|0];
  22. const x = i*fs, y = drops[i]*fs;
  23. ctx.fillStyle = '#9fffc9';
  24. ctx.fillText(ch, x, y);
  25. ctx.fillStyle = '#00ff6a';
  26. ctx.fillText(ch, x, y - fs);
  27. drops[i] += 1;
  28. if (y > k.h && Math.random() > 0.975) drops[i] = 0;
  29. }
  30. });
  31. return { stop(){ stop(); k.destroy(); } };
  32. };
  33. })();