magnetic-field.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. (function(){
  2. window.HPX = window.HPX || {};
  3. window.HPX['magnetic-field'] = function(el){
  4. const U = window.HPX._u;
  5. const k = U.canvas(el), ctx = k.ctx;
  6. const pal = U.palette(el);
  7. const N = 60;
  8. const parts = Array.from({length:N}, (_,i) => ({
  9. phase: Math.random()*Math.PI*2,
  10. freq: U.rand(0.4, 1.2),
  11. amp: U.rand(30, 90),
  12. y0: U.rand(0.15, 0.85),
  13. c: pal[i%pal.length],
  14. trail: []
  15. }));
  16. const stop = U.loop((t) => {
  17. ctx.fillStyle = 'rgba(0,0,0,0.08)';
  18. ctx.fillRect(0,0,k.w,k.h);
  19. for (const p of parts){
  20. const x = ((t*80 + p.phase*50) % (k.w+100)) - 50;
  21. const y = k.h*p.y0 + Math.sin(x*0.02 + p.phase + t*p.freq)*p.amp;
  22. p.trail.push([x,y]);
  23. if (p.trail.length > 18) p.trail.shift();
  24. ctx.strokeStyle = p.c;
  25. ctx.lineWidth = 2;
  26. ctx.beginPath();
  27. for (let i=0;i<p.trail.length;i++){
  28. const [tx,ty] = p.trail[i];
  29. if (i===0) ctx.moveTo(tx,ty); else ctx.lineTo(tx,ty);
  30. }
  31. ctx.globalAlpha = 0.7;
  32. ctx.stroke();
  33. ctx.globalAlpha = 1;
  34. ctx.fillStyle = p.c;
  35. ctx.beginPath(); ctx.arc(x,y,2.5,0,Math.PI*2); ctx.fill();
  36. }
  37. });
  38. return { stop(){ stop(); k.destroy(); } };
  39. };
  40. })();