我正在使用 pdf.js 在画布上渲染 pdf 文件。如何在画布上平移 pdf?我正在尝试一些用于平移的代码,但 chrome 会因此而崩溃。平移的相同代码适用于图像。
让我知道我哪里出错了。
var scale = 1;
var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
function pdfCanvas(scale){
PDFJS.getDocument('gkhead.pdf').then(function(pdf) {
// Using promise to fetch the page
pdf.getPage(1).then(function(page) {
// var scale = 1.5;
var viewport = page.getViewport(scale);
//
// Prepare canvas using PDF page dimensions
//
//canvas.height = viewport.height;
canvas.height = 800;
//canvas.width = viewport.width;
canvas.width = 800;
context.globalAlpha = 0.5;
//
// Render PDF page into canvas context
//
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
context.restore();
});
});
}
尝试以下代码进行平移:
var isDown = false;
var startCoords = [];
var last = [0, 0];
canvas.onmousedown = function(e) {
isDown = true;
startCoords = [
e.offsetX - last[0],
e.offsetY - last[1]
];
};
canvas.onmouseup = function(e) {
isDown = false;
last = [
e.offsetX - startCoords[0], // set last coordinates
e.offsetY - startCoords[1]
];
};
canvas.onmousemove = function(e)
{
if(!isDown) return;
var x = e.offsetX;
var y = e.offsetY;
context.setTransform(1, 0, 0, 1,
x - startCoords[0], y - startCoords[1]);
pdfCanvas(scale)
}