我有一个问题,转换画布到img..使用toDataURL()并将其插入img src的最佳方法是什么?当我启动脚本时,它给了我正确的画布,但img是空白的。这是我的代码:
<!DOCTYPE HTML>
<html>
<head>
<script type='text/javascript' src='//code.jquery.com/jquery-2.2.3.js'></script>
<script type="text/javascript" src="https://raw.github.com/mozilla/pdf.js/gh-pages/build/pdf.js"></script>
</head>
<body>
<div id='anteprima' ></div>
<div id='anteprima_img' ></div>
<script type="text/javascript">
var file = 'http://www.businessmodelgeneration.com/downloads/businessmodelgeneration_preview.pdf';
pdftoimg(file, 1, 0.5, 'anteprima');
function pdftoimg(file, num, scale2, idd) {
PDFJS.disableWorker = true;
PDFJS.getDocument(file).then(function(pdf) {
pdf.getPage(num).then(function(page) {
var canvas = document.createElement('canvas');
canvas.id = 'pag' + num;
canvas.className = 'grande';
canvasContainer = document.getElementById(idd);
var context = canvas.getContext('2d');
var viewport = page.getViewport(scale2);
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
canvasContainer.appendChild(canvas);
var dataUrl = canvas.toDataURL();
image = document.createElement('img');
image.src = dataUrl;
$('#anteprima_img').html(image);
});
});
};
</script>
</body>
</html>
字符串
1条答案
按热度按时间kkih6yb81#
你的代码非常好,你只需要在将其转换为数据URL之前等待渲染画布。
字符串
[NOTE此代码仅适用于PDF.js版本2之前的版本1(当语法发生重大更改时)]
型