Viewer.jsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. import {
  2. Component,
  3. createRef,
  4. Children,
  5. isValidElement,
  6. cloneElement,
  7. } from "react";
  8. import PropTypes from "prop-types";
  9. import { gsap, ScrollTrigger } from "gsap/all";
  10. import LazyLoad from "react-lazyload";
  11. import { css } from "@emotion/react";
  12. // import { Style } from "../style/viewer";
  13. export default function Viewer(props) {
  14. const lazyHeight = 0.01 * parseFloat(props.height) * window.innerHeight;
  15. // offset={1e4}
  16. var allChildren = Children.map(props.children, function (element) {
  17. return isValidElement(element)
  18. ? cloneElement(element, {
  19. parentHeight: props.height,
  20. debug: props.debug,
  21. })
  22. : element;
  23. });
  24. const debug = props.debug || false;
  25. // console.log("lazyHeight", lazyHeight);
  26. return (
  27. <LazyLoad height={lazyHeight} offset={1e4}>
  28. <ViewerInner {...props} debug={debug}>
  29. {allChildren}
  30. </ViewerInner>
  31. </LazyLoad>
  32. );
  33. }
  34. Viewer.propTypes = {
  35. name: PropTypes.string,
  36. height: PropTypes.string,
  37. path: PropTypes.string,
  38. frameCount: PropTypes.number,
  39. startFrame: PropTypes.number,
  40. enterTween: PropTypes.object,
  41. exitTween: PropTypes.object,
  42. canvasSize: PropTypes.array,
  43. pause: PropTypes.object,
  44. children: PropTypes.any,
  45. debug: PropTypes.bool,
  46. scrollSpeed: PropTypes.number,
  47. };
  48. class ViewerInner extends Component {
  49. constructor(props) {
  50. super();
  51. //ref
  52. this.containerRef = createRef(null);
  53. this.viewerRef = createRef(null);
  54. this.canvasContainerRef = createRef(null);
  55. this.loadingWrap = createRef(null);
  56. this.viewerOffsetRef = createRef(null);
  57. this.canvasRef = createRef(null);
  58. this.processingRef = createRef(null);
  59. this.preProcessingRef = createRef(null);
  60. this.processBarRef = createRef(null);
  61. this.sequence = [];
  62. this.loadedRenderPool = [];
  63. this.enterTimeline = false;
  64. this.exitTimeline = false;
  65. this.loadComplete = false;
  66. this.playBarTween = false;
  67. this.playPreBarTween = false;
  68. this.loadedCount = 0;
  69. this.progress = 0;
  70. this.lastFrame = -1;
  71. this.floatFrame = 0;
  72. this.frame = 0;
  73. this.loadedRenderTimeout = null;
  74. this.poolAnimateDelay = 40;
  75. this.context = null;
  76. this.width = 1552;
  77. this.height = 873;
  78. this.justScrolled = false;
  79. this.lastProgress = false;
  80. this.isBelow = true;
  81. this.isAbove = false;
  82. props.debug && console.log("init ", props.name);
  83. }
  84. static propTypes = Viewer.propTypes;
  85. componentWillUnmount() {
  86. this.props.debug && console.warn("remove-timeline");
  87. if (this.timeline) {
  88. this.timeline.kill(true);
  89. }
  90. }
  91. componentDidUpdate() {
  92. if (this.props.debug) {
  93. this.timeline.scrollTrigger.refresh();
  94. }
  95. }
  96. componentDidMount() {
  97. this.fullFrameCount = this.props.frameCount;
  98. this.frame = this.props.startFrame || 0;
  99. if (this.props.pause) {
  100. Object.keys(this.props.pause).forEach((index) => {
  101. this.fullFrameCount += this.props.pause[index];
  102. });
  103. }
  104. this.loadAssets();
  105. this.canvasRef.current && this.initializeCanvas();
  106. if (!this.timeline) {
  107. this.initializeTimeline();
  108. this.setTimeline();
  109. }
  110. if (!this.enterTimeline && this.props.enterTween) {
  111. this.initializeEnterTween();
  112. }
  113. if (!this.exitTimeline && this.props.exitTween) {
  114. this.initializeExitTween();
  115. }
  116. ScrollTrigger.refresh();
  117. }
  118. loadImage(index) {
  119. const img = new Image();
  120. img.retried = 0;
  121. img.src = this.getSourcePath(index);
  122. img.ogSrc = img.src;
  123. if (this.props.pause && index + "" in this.props.pause) {
  124. for (var r = this.props.pause[index]; r--; ) {
  125. this.sequence.push(img);
  126. }
  127. }
  128. this.sequence.push(img);
  129. img.onerror = () => {
  130. var timeStamp = Math.floor(Date.now() * Math.random())
  131. .toString()
  132. .substring(0, 8);
  133. img.retried < 2
  134. ? setTimeout(() => {
  135. img.src = img.ogSrc + "?" + timeStamp;
  136. }, 80)
  137. : img.retried < 3 &&
  138. setTimeout(() => {
  139. img.src = img.ogSrc.slice(0, -4) + ".jpg?" + timeStamp;
  140. }, 80),
  141. img.retried++;
  142. this.props.debug && console.log("img.retried", img.retried);
  143. };
  144. img.onload = () => {
  145. index === 1 && this.renderImageToCanvas(0);
  146. if (
  147. this.frame > index &&
  148. this.timeline &&
  149. this.timeline.scrollTrigger.isActive
  150. ) {
  151. this.poolNewFrames(index - 1);
  152. }
  153. var t = 100 - (this.frame / this.fullFrameCount) * 100 + "%";
  154. if (this.preProcessingRef.current) {
  155. this.preProcessingRef.current.style.width = t;
  156. }
  157. this.loadedCount += 1;
  158. if (this.loadedCount === parseFloat(this.props.frameCount) - 1) {
  159. this.loadingComplete();
  160. }
  161. };
  162. }
  163. getSourcePath(index) {
  164. const defaultPrefix = import.meta.env.VITE_APP_SOURCE;
  165. return `${defaultPrefix}${this.props.path}/${"".concat(
  166. index.toString().padStart(4, "0")
  167. )}.webp`;
  168. }
  169. loadAssets() {
  170. this.loadImage(1);
  171. setTimeout(() => {
  172. for (var t = 2; t <= this.props.frameCount; t += 1) {
  173. this.loadImage(t);
  174. }
  175. }, 60);
  176. }
  177. loadingComplete() {
  178. console.log(this.props.path, "loading complete");
  179. this.loadComplete = true;
  180. this.isAbove && this.renderImageToCanvas(this.loadedCount - 1);
  181. }
  182. initializeCanvas() {
  183. this.context = this.canvasRef.current.getContext("2d", {
  184. alpha: false,
  185. desynchronized: true,
  186. powerPreference: "high-performance",
  187. });
  188. this.context.imageSmoothingEnabled = true;
  189. this.context.imageSmoothingQuality = "high";
  190. }
  191. initializeTimeline() {
  192. // const openLoading = () => {
  193. // gsap.to(this.loadingWrap.current, {
  194. // autoAlpha: 1,
  195. // });
  196. // };
  197. // const closeLoading = () => {
  198. // gsap.to(this.loadingWrap.current, {
  199. // autoAlpha: 0,
  200. // });
  201. // };
  202. // closeLoading();
  203. this.timeline = gsap.timeline({
  204. scrollTrigger: {
  205. trigger: this.containerRef.current,
  206. pin: this.viewerRef.current,
  207. scrub: 0.66,
  208. start: "top top",
  209. end: "bottom bottom",
  210. ease: "none",
  211. markers: this.props.debug || false,
  212. onUpdate: (trigger) => {
  213. //处理processloading
  214. if (!this.lastProgress) {
  215. this.lastProgress = trigger.progress;
  216. } else {
  217. if (this.lastProgress !== this.progress) {
  218. this.justScrolled = true;
  219. this.lastProgress = trigger.progress;
  220. }
  221. }
  222. },
  223. onScrubComplete: () => {
  224. this.justScrolled = true;
  225. },
  226. onEnter: () => {
  227. this.isAbove = false;
  228. console.log(this.props.path, "onEnter");
  229. this.enterShowElements();
  230. },
  231. onEnterBack: () => {
  232. // openLoading();
  233. console.log(this.props.path, "onEnterBack");
  234. this.isBelow = false;
  235. this.enterShowElements();
  236. },
  237. onLeave: () => {
  238. console.log(this.props.path, "onLeave");
  239. this.isAbove = true;
  240. this.leaveHideElements();
  241. },
  242. onLeaveBack: () => {
  243. console.log(this.props.path, "onLeaveBack");
  244. this.isBelow = true;
  245. this.leaveHideElements();
  246. },
  247. },
  248. });
  249. }
  250. setTimeline() {
  251. this.timeline.to(this, {
  252. floatFrame: this.fullFrameCount - 1,
  253. ease: "none",
  254. onUpdate: () => {
  255. this.frame = Math.floor(this.floatFrame);
  256. if (
  257. this.lastFrame === this.frame ||
  258. this.loadedRenderPool.length === 0
  259. ) {
  260. this.renderImageToCanvas(this.frame);
  261. }
  262. },
  263. });
  264. }
  265. initializeEnterTween() {
  266. const duration = this.props.enterTween.duration || 1;
  267. let openPin = false;
  268. // console.warn("this.props.enterTween", duration, this.props.enterTween);
  269. gsap.set(this.viewerRef.current, {
  270. yPercent: -100 * duration,
  271. });
  272. if (void 0 !== this.props.enterTween.pin) {
  273. openPin = this.props.enterTween.pin;
  274. }
  275. this.enterTimeline = gsap.timeline({
  276. scrollTrigger: {
  277. trigger: this.viewerRef.current,
  278. scrub: true,
  279. pin: openPin,
  280. start: function () {
  281. return "top top";
  282. },
  283. end: function () {
  284. return "top top-=" + window.innerHeight * duration;
  285. },
  286. },
  287. });
  288. if (this.props.enterTween.to) {
  289. this.enterTimeline.to(
  290. this.viewerRef.current,
  291. Object.assign(
  292. {
  293. ease: "none",
  294. },
  295. this.props.enterTween.to
  296. )
  297. );
  298. }
  299. if (this.props.enterTween.from) {
  300. this.enterTimeline.from(
  301. this.viewerRef.current,
  302. Object.assign(
  303. {
  304. ease: "none",
  305. },
  306. this.props.enterTween.from
  307. )
  308. );
  309. }
  310. }
  311. initializeExitTween() {
  312. console.log(this.props.path, "initializing exit tween ");
  313. this.exitTimeline = gsap.timeline({
  314. scrollTrigger: {
  315. scrub: true,
  316. trigger: this.containerRef.current,
  317. pin: this.viewerRef.current,
  318. onLeave: this.props.exitTween.onLeave,
  319. onLeaveBack: this.props.exitTween.onLeaveBack,
  320. onEnterBack: this.props.exitTween.onEnterBack,
  321. start: function () {
  322. return "bottom bottom";
  323. },
  324. end: function () {
  325. return "bottom top";
  326. },
  327. },
  328. });
  329. if (this.props.exitTween.from) {
  330. this.exitTimeline.from(
  331. this.viewerRef.current,
  332. Object.assign(
  333. {
  334. ease: "none",
  335. },
  336. this.props.exitTween.from
  337. )
  338. );
  339. }
  340. if (this.props.exitTween.to) {
  341. this.exitTimeline.to(
  342. this.viewerRef.current,
  343. Object.assign(
  344. {
  345. ease: "none",
  346. },
  347. this.props.exitTween.to
  348. )
  349. );
  350. }
  351. }
  352. poolNewFrames(index) {
  353. this.loadedRenderPool.unshift(index);
  354. this.loadedRenderPool.sort(function (a, b) {
  355. return b - a;
  356. });
  357. this.animatePool();
  358. }
  359. animatePool() {
  360. if (!this.loadedRenderTimeout && this.loadedRenderPool.length) {
  361. this.loadedRenderTimeout = setTimeout(() => {
  362. this.loadedRenderTimeout = false;
  363. var poolFrame = this.loadedRenderPool[this.loadedRenderPool.length - 1];
  364. if (poolFrame <= this.frame) {
  365. var remainFrame = this.loadedRenderPool.pop();
  366. this.renderImageToCanvas(remainFrame);
  367. this.animatePool();
  368. }
  369. if (this.frame < poolFrame) {
  370. this.loadedRenderPool = [];
  371. }
  372. }, this.poolAnimateDelay);
  373. }
  374. }
  375. renderImageToCanvas(index) {
  376. if (this.sequence[index]) {
  377. if (this.context.drawImage) {
  378. this.context.drawImage(this.sequence[index], 0, 0);
  379. this.lastFrame = index;
  380. this.handleSyncProessBar(index);
  381. } else {
  382. this.initializeCanvas();
  383. }
  384. }
  385. }
  386. handleSyncProessBar(index) {
  387. const progressingPreload =
  388. 100 - (this.frame / this.fullFrameCount) * 100 + "%";
  389. const progressing = 100 - (index / this.fullFrameCount) * 100 + "%";
  390. // console.log("handleSyncProessBar", this.processingRef.current);
  391. if (this.preProcessingRef.current) {
  392. this.playPreBarTween = gsap.to(this.preProcessingRef.current, {
  393. duration: 0.05,
  394. right: progressingPreload,
  395. ease: "none",
  396. });
  397. this.playBarTween = gsap.to(this.processingRef.current, {
  398. duration: 0.05,
  399. right: progressing,
  400. ease: "none",
  401. });
  402. }
  403. }
  404. enterShowElements() {
  405. gsap.set(this.processBarRef.current, {
  406. autoAlpha: 1,
  407. });
  408. }
  409. leaveHideElements() {
  410. gsap.set(this.processBarRef.current, {
  411. autoAlpha: 0,
  412. });
  413. }
  414. render() {
  415. return (
  416. <>
  417. <div
  418. className={`processBar ${this.props.name}`}
  419. ref={this.processBarRef}
  420. css={css`
  421. position: fixed;
  422. top: calc(100vh - 4px);
  423. top: calc(var(--vh, 1vh) * 100 - 4px);
  424. left: 0;
  425. width: 100vw;
  426. max-width: 100%;
  427. border-top: 1px solid rgba(33, 33, 44, 0.6);
  428. background-color: rgba(17, 17, 34, 0.6);
  429. height: 4px;
  430. z-index: 9;
  431. visibility: hidden;
  432. `}
  433. >
  434. <div
  435. css={css`
  436. position: absolute;
  437. width: auto;
  438. height: 4px;
  439. left: 0;
  440. bottom: 0;
  441. z-index: 10;
  442. background-color: rgba(120, 120, 163, 0.33);
  443. `}
  444. ref={this.preProcessingRef}
  445. ></div>
  446. <div
  447. css={css`
  448. position: absolute;
  449. width: auto;
  450. height: 4px;
  451. left: 0;
  452. bottom: 0;
  453. z-index: 10;
  454. background-color: hsla(0, 0%, 79.2%, 0.5);
  455. `}
  456. ref={this.processingRef}
  457. ></div>
  458. </div>
  459. <div
  460. css={css`
  461. position: relative;
  462. margin: auto;
  463. text-align: center;
  464. pointer-events: none;
  465. max-width: 100vw;
  466. `}
  467. ref={this.containerRef}
  468. style={{ height: this.props.height || "500vh" }}
  469. >
  470. <div ref={this.viewerRef}>
  471. <div style={{ overflow: "hidden" }}>
  472. <canvas
  473. css={css`
  474. width: auto;
  475. margin-left: 50%;
  476. transform: translateX(-50%);
  477. height: 100vh;
  478. height: calc(var(--vh, 1vh) * 100);
  479. `}
  480. ref={this.canvasRef}
  481. width={this.width}
  482. height={this.height}
  483. ></canvas>
  484. </div>
  485. </div>
  486. <>{this.props.children}</>
  487. </div>
  488. </>
  489. );
  490. }
  491. }