我正在使用 react-stl-viewer 为我的网站渲染 STL 文件。文件渲染后,我想捕获 2D 图像以在网站的其他地方使用。有没有办法使用这个包来实现这一点?
这是提供的示例代码:
import React from 'react';
import ReactDOM from 'react-dom';
import {StlViewer} from "react-stl-viewer";
const url = "https://storage.googleapis.com/ucloud-v3/ccab50f18fb14c91ccca300a.stl"
const style = {
top: 0,
left: 0,
width: '100vw',
height: '100vh',
}
function App() {
return (
<StlViewer
style={style}
orbitControls
shadows
url={url}
/>
);
}
ReactDOM.render(<App/>, document.getElementById('root'));
找到解决办法了!如果您保留对 STLViewer 的 canvas 元素的引用,则可以调用
toBlob()
并将 blob 转换为图像文件。
这是使用给定示例的完整代码:
import React, { useEffect, useState } from 'react';
import { StlViewer } from 'react-stl-viewer';
const url =
'https://storage.googleapis.com/ucloud-v3/ccab50f18fb14c91ccca300a.stl';
const style = {
top: 0,
left: 0,
width: '100vw',
height: '100vh',
};
function App() {
const [viewerElement, setViewerElement] = useState(null);
const captureThumbnail = () => {
if (viewerElement) {
const canvas = viewerElement.querySelector('canvas');
if (canvas) {
canvas.toBlob((blob) => {
const file = new File([blob], "my-snapshot.jpg");
// Do something with the image file
});
}
}
}
useEffect(() => {
if (viewerElement) {
captureThumbnail();
}
}, [viewerElement]);
return (
<div>
<div ref={setViewerElement}>
<StlViewer style={style} orbitControls shadows url={url}/>
</div>
</div>
);
}
export default App;