_util.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* html-ppt fx :: shared helpers */
  2. (function(){
  3. window.HPX = window.HPX || {};
  4. const U = window.HPX._u = {};
  5. U.css = (el, name, fb) => {
  6. const v = getComputedStyle(el).getPropertyValue(name).trim();
  7. return v || fb;
  8. };
  9. U.accent = (el, fb) => U.css(el, '--accent', fb || '#7c5cff');
  10. U.accent2 = (el, fb) => U.css(el, '--accent-2', fb || '#22d3ee');
  11. U.text = (el, fb) => U.css(el, '--text-1', fb || '#eaeaf2');
  12. U.palette = (el) => [
  13. U.accent(el, '#7c5cff'),
  14. U.accent2(el, '#22d3ee'),
  15. U.css(el, '--ok', '#22c55e'),
  16. U.css(el, '--warn', '#f59e0b'),
  17. U.css(el, '--danger', '#ef4444'),
  18. ];
  19. U.canvas = (el) => {
  20. if (getComputedStyle(el).position === 'static') el.style.position = 'relative';
  21. const c = document.createElement('canvas');
  22. c.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;pointer-events:none;display:block;';
  23. el.appendChild(c);
  24. const ctx = c.getContext('2d');
  25. let w = 0, h = 0, dpr = Math.max(1, Math.min(2, window.devicePixelRatio||1));
  26. const fit = () => {
  27. const r = el.getBoundingClientRect();
  28. w = Math.max(1, r.width|0);
  29. h = Math.max(1, r.height|0);
  30. c.width = (w*dpr)|0;
  31. c.height = (h*dpr)|0;
  32. ctx.setTransform(dpr,0,0,dpr,0,0);
  33. };
  34. fit();
  35. const ro = new ResizeObserver(fit);
  36. ro.observe(el);
  37. return {
  38. c, ctx,
  39. get w(){return w;}, get h(){return h;}, get dpr(){return dpr;},
  40. destroy(){
  41. try{ro.disconnect();}catch(e){}
  42. if (c.parentNode) c.parentNode.removeChild(c);
  43. }
  44. };
  45. };
  46. U.loop = (fn) => {
  47. let raf = 0, stopped = false, t0 = performance.now();
  48. const tick = (t) => {
  49. if (stopped) return;
  50. fn((t - t0)/1000);
  51. raf = requestAnimationFrame(tick);
  52. };
  53. raf = requestAnimationFrame(tick);
  54. return () => { stopped = true; cancelAnimationFrame(raf); };
  55. };
  56. U.rand = (a,b) => a + Math.random()*(b-a);
  57. })();