constellation.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. (function(){
  2. window.HPX = window.HPX || {};
  3. window.HPX['constellation'] = function(el){
  4. const U = window.HPX._u;
  5. const k = U.canvas(el), ctx = k.ctx;
  6. const ac = U.accent(el,'#9fb4ff');
  7. const N = 70;
  8. let pts = [];
  9. const seed = () => {
  10. pts = Array.from({length:N}, () => ({
  11. x: Math.random()*k.w, y: Math.random()*k.h,
  12. vx: U.rand(-0.3,0.3), vy: U.rand(-0.3,0.3)
  13. }));
  14. };
  15. seed();
  16. let lw=k.w, lh=k.h;
  17. const stop = U.loop(() => {
  18. if (k.w!==lw||k.h!==lh){ seed(); lw=k.w; lh=k.h; }
  19. ctx.clearRect(0,0,k.w,k.h);
  20. for (const p of pts){
  21. p.x += p.vx; p.y += p.vy;
  22. if (p.x<0||p.x>k.w) p.vx*=-1;
  23. if (p.y<0||p.y>k.h) p.vy*=-1;
  24. }
  25. for (let i=0;i<N;i++){
  26. for (let j=i+1;j<N;j++){
  27. const a=pts[i], b=pts[j];
  28. const d = Math.hypot(a.x-b.x, a.y-b.y);
  29. if (d < 150){
  30. ctx.globalAlpha = 1 - d/150;
  31. ctx.strokeStyle = ac; ctx.lineWidth=1;
  32. ctx.beginPath(); ctx.moveTo(a.x,a.y); ctx.lineTo(b.x,b.y); ctx.stroke();
  33. }
  34. }
  35. }
  36. ctx.globalAlpha = 1;
  37. ctx.fillStyle = ac;
  38. for (const p of pts){
  39. ctx.beginPath(); ctx.arc(p.x,p.y,1.8,0,Math.PI*2); ctx.fill();
  40. }
  41. });
  42. return { stop(){ stop(); k.destroy(); } };
  43. };
  44. })();