Somebody help me intergrate turnjs to help while flipping through book pages. I am successfully able to render a pdf and even display it and using buttons move to next/previous page. But I want to add flipping effect as I navigate from one page to the next. turn.js does it well. this is the link: http://www.turnjs.com/
.
currently this is my template:
<div class="flex justify-between w-full mt-2">
<.button class="js-prev" type="button">Prev</.button>
<input class="js-zoom" type="range" value="1.5" min="0" max="2" step=".1" />
<.button class="js-next" type="button">Next</.button>
</div>
<div class="flex justify-left mb-16 mt-2 mx-4 ">
<canvas
class="mt-1"
phx-hook="PDF"
id="pdf-canvas"
data-path={Routes.upload_book_path(@socket, :book, @book_id)}
>
</canvas>
</div>
and my pdfjs hook:
import pdfJS from 'pdfjs-dist';
import 'pdfjs-dist/build/pdf.worker.entry';
function renderPDF(canvas) {
let currentPageNum = 1;
// Handle hidi
const outputScale = window.devicePixelRatio || 1;
function adjustCanvasSize(viewport) {
canvas.width = Math.floor(viewport.width * outputScale);
canvas.height = Math.floor(viewport.height * outputScale);
canvas.style.width = Math.floor(viewport.width) + 'px';
canvas.style.height = Math.floor(viewport.height) + 'px';
}
const loadingTask = pdfJS.getDocument(canvas.dataset.path);
(async () => {
const pdf = await loadingTask.promise;
let page = await pdf.getPage(1);
const viewport = page.getViewport({ scale: 1.5 });
const context = canvas.getContext('2d');
adjustCanvasSize(viewport);
canvas.classList.add('border', 'border-purple-500', 'rounded');
const transform = outputScale !== 1
? [outputScale, 0, 0, outputScale, 0, 0]
: null;
let renderContext = {
canvasContext: context,
transform,
viewport,
};
page.render(renderContext);
async function onPrevPage() {
if (currentPageNum <= 1) {
return;
}
currentPageNum -= 1;
page = await pdf.getPage(currentPageNum);
page.render(renderContext);
}
async function onNextPage() {
if (currentPageNum >= pdf.numPages) {
return;
}
currentPageNum += 1;
page = await pdf.getPage(currentPageNum);
page.render(renderContext);
}
async function onZoom(e) {
const newViewport = page.getViewport({ scale: parseFloat(e.target.value) });
adjustCanvasSize(newViewport);
renderContext.viewport = newViewport;
page = await pdf.getPage(currentPageNum);
page.render(renderContext);
}
document.querySelector('.js-next').addEventListener('click', onNextPage);
document.querySelector('.js-prev').addEventListener('click', onPrevPage)
document.querySelector('.js-zoom').addEventListener('click', onZoom)
})();
}
export default {
mounted() {
renderPDF(this.el);
},
updated() {
renderPDF(this.el);
},
};
and this is how I retrieve a book:
def book(conn, %{"upload_id" => id}) do
upload = Documents.get_upload!(id)
book_path = Upload.local_path(upload.id, upload.filename, conn.assigns.current_user.id)
conn
|> put_resp_content_type("application/pdf ")
|> send_file(200, book_path)
end