这个问题的解决方法是在A-Frame场景中使用pdf.js来加载PDF文件,但在VR模式下,无法更新画布纹理两次。解决方案是调用“pdf.js”中的“PDFJS.disableWorker = true;”命令来禁用“worker”,使其在单线程环境中工作。这种方法已在下面的示例代码中说明。
示例代码:
AFRAME.registerComponent('pdf', { schema: {src: {type: 'string'}},
init: function () { var self = this; var el = this.el;
PDFJS.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';
PDFJS.disableWorker = true;
PDFJS.getDocument(this.data.src).then(function (doc) {
self.doc = doc;
el.emit('pdf-loaded');
});
},
getPageDimensions: function (pageNumber) { var pdfPage = this.doc.getPage(pageNumber); var viewport = pdfPage.getViewport(1); return {width: viewport.width, height: viewport.height}; } });
AFRAME.registerComponent('pdf-page', { schema: {pageNumber: {type: 'number', default: 1}},
init: function () { var el = this.el; var dimensions = el.sceneEl.components.pdf.getPageDimensions(this.data.pageNumber); el.setAttribute('geometry', 'primitive: plane; height: ' + dimensions.height * 0.01 + '; width: ' + dimensions.width * 0.01); el.setAttribute('material', 'shader: flat; side: double'); this.renderPage(); },
renderPage: function () { var self = this; var el = this.el;
this.el.sceneEl.components.pdf.doc.getPage(this.data.pageNumber).then(function (page) {
var viewport = page.getViewport(1);
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var cssScale = 1 / viewport.scale;
canvas.height = viewport.height * cssScale;
canvas.width = viewport.width * cssScale;
var task = page.render({canvasContext: context, viewport: viewport});
task.promise.then(function () {
el.setAttribute('material', 'src: ' + canvas.toDataURL());
});
});
} });