我正在尝试截取模型查看器显示的 .glb 文件的屏幕截图。但我无法找到解决方案。 我在某处读到关键是将模型查看器转换为 blob 对象,然后下载图像。
<div class="button">
<a id="download" href="#">Download button</a>
</div>
<script>
function download() {
const modelViewer = document.querySelector("#modelviewertest");
const screenshot = URL.createObjectURL(
modelViewer.toBlob("image/jpeg")
);
const donwloadLink = document.querySelector("#download");
donwloadLink.download = screenshot;
donwloadLink.href = data;
}
我曾尝试使用 html2canvas 截屏,但无法正常工作。我想在我的服务器中保存模型查看器上加载的 glb 模型的屏幕截图。
这里有截图下载的例子。此处列出了代码以防链接断开。归因于 GitHub 上的@milesgreen,通过此 issue.
发布const modelViewer = document.getElementById("viewer");
async function downloadPosterToBlob() {
const blob = await modelViewer.toBlob({ idealAspect: false });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "modelViewer_toBlob.png";
a.click();
URL.revokeObjectURL(url);
}
function downloadPosterToDataURL() {
const url = modelViewer.toDataURL();
const a = document.createElement("a");
a.href = url;
a.download = "modelViewer_toDataURL.png";
a.click();
URL.revokeObjectURL(url);
}
上面的 JavaScript 引用了一个 ID 设置为“viewer”的 HTML 元素。
<model-viewer id="viewer"
alt="Two cylinder engine"
src="models/2CylinderEngine.glb"
shadow-intensity="1"
camera-controls touch-action="pan-y">
</model-viewer>
在HTML中添加一个按钮并连接到它的
click
事件来触发上面的下载功能:
document.querySelector("#download-button").addEventListener("click", downloadPosterToBlob);
<button id="download-button">Download</button>
参考模型查看器网络组件的
toBlob()
方法。