Zic*_*ang 0 html javascript reactjs
我是react.js 和Javascript 的新手。我的工作是在图片上方添加一个下载按钮,点击后就会下载SVG格式的图片。我有一种方法有效,我将下载函数写入图像生成文件中,并调用该函数。但是只要我需要添加更多按钮,我发现图像svg文件在html页面里面。为什么我不能直接将 svg 内容保存到文件中。例如:按钮下载内容在我的react.js代码中,RankedBarchart渲染就是我想要的。有什么方法可以直接获取内容或下载内容。
<h2>
BMC values: sorted by {chartName}{' '}
<button onClick={plot_download_form} class="btn btn-primary">
Export plot
</button>
</h2>
<RankedBarchart
// the visualization function not affect the plot
// the selectedAxis is the main function to show tables,
// check the RankedBarchart file, selectedAxis part
data={plotData}
visualization={this.props.visualization}
selectedAxis={this.props.selectedAxis}
/>
Run Code Online (Sandbox Code Playgroud)
如果您的 SVG 位于 DOM 内部,您可以使用 ref 或类似的东西document.querySelector来访问 DOM 元素。您需要获取对包装元素的引用并访问wrapperElement.innerHTML。然后,将其包装在 blob 中并创建下载链接。
function downloadBlob(blob, filename) {
const objectUrl = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = objectUrl;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
setTimeout(() => URL.revokeObjectURL(objectUrl), 5000);
}
export function MyComponent() {
const svgRef = useRef();
const downloadSVG = useCallback(() => {
const svg = svgRef.current.innerHTML;
const blob = new Blob([svg], { type: "image/svg+xml" });
downloadBlob(blob, `myimage.svg`);
}, []);
return (
<div className="App">
<div ref={svgRef}>
<svg>
{/* svg or react component generating svg */}
</svg>
</div>
<div>
<button onClick={downloadSVG}>Download</button>
</div>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
我做了一个codesandbox示例:https://codesandbox.io/s/svg-dom-download-example-mmnd1? file=/src/App.js
| 归档时间: |
|
| 查看次数: |
3595 次 |
| 最近记录: |