当前位置:   article > 正文

前端pdf-阅读器-3d版_js pdf的翻页效果

js pdf的翻页效果

目录

一、基于pdf.js、turnjs4封装的3d翻页效果pdf文件阅读器、pdf文件url拼接地址栏就可以展示、兼容pc端、H5端

二、效果展示图

三、部分源码

四、点赞关注加收藏私信我发源码(记得私信我、发邮箱哈)


一、基于pdf.js、turnjs4封装的3d翻页效果pdf文件阅读器、pdf文件url拼接地址栏就可以展示、兼容pc端、H5端

二、效果展示图

 

三、部分源码

  1. <script>
  2. /*定义变量参数 */
  3. // 定义一个空字符串变量用于存储PDF文件的URL
  4. var pdfurl = "";
  5. // 获取flipbook元素,该元素将被用来呈现翻页效果
  6. var flipbook = $("#flipbook");
  7. // 初始化当前页码为1
  8. var pageCurrent = 0;
  9. // 设置书本ID,可以根据需要进行更改
  10. var bid = 1;
  11. // 初始化缩放比例和旋转角度为1(即不缩放、不旋转)
  12. var scale = 1;
  13. var rotate = 1;
  14. // 初始化画布宽度和高度为空值,在后续代码中会动态设置这些值
  15. var canvasWidth = null;
  16. var canvasHeight = null;
  17. const getUrlParam = (name) => {
  18. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
  19. var r = window.location.search.substring(1).match(reg); //匹配目标参数
  20. if (r != null) return decodeURI(r[2]);
  21. return null; //返回参数值
  22. };
  23. const isMobile = () => {
  24. // 检查用户代理是否包含“Mobi”子字符串
  25. return /Mobi/.test(navigator.userAgent);
  26. };
  27. const disableScroll = () => {
  28. // 获取当前垂直滚动位置
  29. let scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  30. // 禁用默认的窗口滚动行为
  31. const preventDefault = (e) => {
  32. e.preventDefault();
  33. };
  34. // 在触摸设备上,禁用touchmove事件来防止页面滑动。
  35. document.body.addEventListener("touchmove", preventDefault, {
  36. passive: false,
  37. });
  38. //在非触摸设备上,阻止窗口滚动事件并将其替换为preventDefault函数。
  39. window.addEventListener("scroll", preventDefault);
  40. // 将body元素的样式设置为固定,并将其上一个滚动位置应用于它。
  41. document.body.style.position = "fixed";
  42. document.body.style.top = -scrollTop + "px";
  43. };
  44. const preloadPdf = async (url) => {
  45. const response = await fetch(url);
  46. const arrayBuffer = await response.arrayBuffer();
  47. return pdfjsLib.getDocument(arrayBuffer);
  48. };
  49. // 在页面加载时就开始预加载PDF文件
  50. window.addEventListener("load", async () => {
  51. if (getUrlParam("pdfurl") != null) {
  52. pdfurl = getUrlParam("pdfurl");
  53. getpdf(pdfurl);
  54. var vConsole = new VConsole();
  55. disableScroll();
  56. console.log(pdfurl);
  57. } else {
  58. alert("文件为空");
  59. }
  60. });
  61. const getpdf = async (url) => {
  62. const loadingTask = pdfjsLib.getDocument(url);
  63. const pdf = await loadingTask.promise;
  64. // 获取第一页的视图,并根据其宽度设置 flipbook 的宽度
  65. const firstPage = await pdf.getPage(1);
  66. const viewport = firstPage.getViewport({ scale: scale });
  67. const mobieWidth = viewport.width * 2;
  68. const pcWidth = viewport.width * 2;
  69. const pdfWidth = isMobile() ? mobieWidth : pcWidth;
  70. const canvasCache = {};
  71. // 一次性获取所有页面的canvas对象,并将其缓存起来
  72. for (let i = 1; i <= pdf.numPages; i++) {
  73. const id = "canvaspage" + i;
  74. const div = document.createElement("div");
  75. div.innerHTML = `<canvas id="${id}" class="page"></canvas>`;
  76. flipbook.append(div);
  77. const page = await pdf.getPage(i);
  78. const canvas = await setcanvas(page, id);
  79. canvasCache[id] = canvas;
  80. }
  81. // 加载turn.js并设置参数
  82. await new Promise((resolve) => {
  83. yepnope({
  84. test: Modernizr.csstransforms,
  85. yep: ["./JS/turnjs4/lib/turn.js"],
  86. complete: () => {
  87. $("#flipbook").turn({
  88. width: pdfWidth,
  89. height: viewport.height,
  90. elevation: 50,
  91. display: isMobile() ? "single" : "double",
  92. autoCenter: true,
  93. duration: 1000,
  94. gradients: true,
  95. disable: true,
  96. // 添加turn.js的turned事件回调函数,用于预加载相邻页面
  97. // 预加载相邻页面的数量可以根据实际情况调整
  98. turned: async function (event, page = 1) {
  99. console.log(event, page, "33333333333333");
  100. const prevPage = page - 1;
  101. const nextPage = page + 1;
  102. // 预加载当前页面的相邻页面
  103. if (prevPage > 0 && !canvasCache[prevPage]) {
  104. const id = "canvaspage" + prevPage;
  105. const div = document.createElement("div");
  106. div.innerHTML = `<canvas id="${id}" class="page"></canvas>`;
  107. flipbook.append(div);
  108. const page = await pdf.getPage(prevPage);
  109. const canvas = await setcanvas(page, id);
  110. canvasCache[prevPage] = canvas;
  111. }
  112. if (nextPage <= pdf.numPages && !canvasCache[nextPage]) {
  113. const id = "canvaspage" + nextPage;
  114. const div = document.createElement("div");
  115. div.innerHTML = `<canvas id="${id}" class="page"></canvas>`;
  116. flipbook.append(div);
  117. const page = await pdf.getPage(nextPage);
  118. const canvas = await setcanvas(page, id);
  119. canvasCache[nextPage] = canvas;
  120. }
  121. // 移除未缓存的旧页面
  122. const unloadPage = isMobile() ? page + 2 : page + 4;
  123. const unloadPage2 = isMobile() ? page - 2 : page - 4;
  124. if (canvasCache[unloadPage]) {
  125. const canvas = canvasCache[unloadPage];
  126. delete canvasCache[unloadPage];
  127. canvas.parentNode.remove();
  128. }
  129. if (canvasCache[unloadPage2]) {
  130. const canvas = canvasCache[unloadPage2];
  131. delete canvasCache[unloadPage2];
  132. canvas.parentNode.remove();
  133. }
  134. },
  135. });
  136. resolve();
  137. },
  138. });
  139. });
  140. // 预加载所有canvas对象的图像数据
  141. Object.values(canvasCache).forEach((canvas) => {
  142. const context = canvas.getContext("2d");
  143. const imageData = context.getImageData(
  144. 0,
  145. 0,
  146. canvas.width,
  147. canvas.height
  148. );
  149. });
  150. // 使用pdf.js库解析PDF文档并返回Promise对象,在解析完成后隐藏遮罩层。
  151. const response = await fetch(url);
  152. const arrayBuffer = await response.arrayBuffer();
  153. const pdfData = new Uint8Array(arrayBuffer);
  154. await pdfjsLib.getDocument(pdfData).promise;
  155. $("#overlay").hide();
  156. };
  157. const canvasCache = {};
  158. const setcanvas = async (page, id) => {
  159. const canvas = document.getElementById(id);
  160. const canvasRect = canvas.getBoundingClientRect();
  161. const isVisible =
  162. canvasRect.bottom > 0 &&
  163. canvasRect.top < window.innerHeight &&
  164. canvasRect.right > 0 &&
  165. canvasRect.left < window.innerWidth;
  166. if (isVisible) {
  167. // 如果 canvas 可见,则将其添加到缓存中
  168. canvasCache[id] = canvas;
  169. } else {
  170. // 如果 canvas 不可见,则从缓存中删除它
  171. delete canvasCache[id];
  172. }
  173. if (!canvas) {
  174. console.log("Canvas element with ID " + id + " not found.");
  175. return;
  176. }
  177. const context = canvas.getContext("2d");
  178. if (!context) {
  179. console.log("Could not get 2D context for canvas element.");
  180. return;
  181. }
  182. const viewport = page.getViewport({ scale: scale });
  183. const screenWidth = Math.min(window.innerWidth, window.innerHeight);
  184. const newScale = screenWidth / viewport.width;
  185. const newViewport = page.getViewport({ scale: newScale });
  186. const outputScale = window.devicePixelRatio;
  187. canvas.width = Math.floor(newViewport.width * outputScale);
  188. canvas.height = Math.floor(newViewport.height * outputScale);
  189. canvas.style.width = "100%";
  190. canvas.style.height = "100%";
  191. const transform =
  192. outputScale !== 1 ? [outputScale, 0, 0, outputScale, 0, 0] : null;
  193. const renderContext = {
  194. canvasContext: context,
  195. transform: transform,
  196. viewport: newViewport,
  197. };
  198. await page.render(renderContext).promise;
  199. return canvas;
  200. };
  201. $(function () {
  202. $(".flip_button_left").bind("click", function () {
  203. $("#flipbook").turn("previous");
  204. });
  205. $(".flip_button_right").bind("click", function () {
  206. $("#flipbook").turn("next");
  207. });
  208. });
  209. </script>

四、点赞关注加收藏私信我发源码(记得私信我、发邮箱哈)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/314673
推荐阅读
相关标签
  

闽ICP备14008679号