summaryrefslogtreecommitdiffhomepage
path: root/vhosts/blog/public/slide.js
blob: 4c7a0de825be2c0ed996f79be7dc8d595b040888 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { GlobalWorkerOptions, getDocument } from "/pdf.min.mjs";

document.addEventListener("DOMContentLoaded", async () => {
  GlobalWorkerOptions.workerSrc = "/pdf.worker.min.mjs";

  const canvas = document.getElementById("slide");
  const ctx = canvas.getContext("2d");
  const url = canvas.dataset.slideLink;

  let pageNum = 1;
  let pageNumPending = null;
  let pageRendering = false;
  let doc = null;

  const renderPage = async (num) => {
    pageRendering = true;
    const page = await doc.getPage(num);

    const viewport = page.getViewport({ scale: 1.0 });
    canvas.height = viewport.height;
    canvas.width = viewport.width;

    // TODO: error handling
    await page.render({
      canvasContext: ctx,
      viewport: viewport,
    });

    pageRendering = false;
    if (pageNumPending !== null) {
      renderPage(pageNumPending);
      pageNumPending = null;
    }
  };

  const queueRenderPage = (num) => {
    if (pageRendering) {
      pageNumPending = num;
    } else {
      renderPage(num);
    }
  };

  const prev = document.getElementById("prev");
  prev.addEventListener("click", () => {
    if (pageNum <= 1) return;
    pageNum--;
    queueRenderPage(pageNum);
  });
  const next = document.getElementById("next");
  next.addEventListener("click", () => {
    if (pageNum >= doc.numPages) return;
    pageNum++;
    queueRenderPage(pageNum);
  });

  // TODO: error handling
  doc = await getDocument(url).promise;
  queueRenderPage(pageNum);
});