首先需要使用html2canvas
import html2canvas from "html2canvas";
在你本来的页面写好一段需要保存为图片的内容,默认为不显示
<button onClick={() => this.downLoadDetail()}>保存图片</button>
<div className="container"
style={{
position: "absolute",
opacity: "0",
maxHeight: "0",
overflow: "hidden",
}}
>
12345
</div>
图片生成以及保存的代码如下
downLoadDetail = async () => {
this.createDetailsImg()
}
async createDetailsImg() {
const { language } = this.props
//图片样式
const text = `
<style>
.container {
display: flex
flex-direction: column
width: 100vw
height: 100vh
padding: 80px 20px 30px
}
</style>
`
const iframe = document.createElement("iframe")
document.body.appendChild(iframe)
iframe.contentWindow.document.body.innerHTML = text + window.document.getElementById("download-div-hidden").innerHTML
iframe.style.width = "100vw"
iframe.style.height = "100vh"
iframe.style.position = "fixed"
iframe.style.left = "-9999px"
iframe.style.top = "-9999px"
try {
try {
const canvas = await html2canvas(iframe.contentWindow.document.body)
const link = canvas.toDataURL("image/jpg")
if (link) {
this.saveImg(`${language.margin_transfer}.jpg`, link)
}
} catch (err) {
console.log(err, "error")
}
} finally {
iframe.remove()
}
}
saveImg(download, href) {
const a = document.createElement("a")
a.download = download
a.href = href
document.body.appendChild(a)
a.click()
a.remove()
}