JavaScript复制图片和下载图片到本地
基本代码结构
<div className="html-canvas-wrap" ref={canvasWrap}>
<div className="html-canvas">
<h3>标题</h3>
<p>标题描述</p>
<img src={TestImg} alt="" />
</div>
<button onClick={handleCopy}>execCommend copy</button>
<button onClick={handleCopy2}>clipboard copy</button>
<button onClick={handleSave}>保存图片到本地</button>
</div>
该功能依赖 html2anvas
npm i -S html2canvas
复制图片
execCommand
经测试在大多数社交工具中粘贴不可用
const handleCopy = () => {
html2canvas(document.querySelector('.html-canvas'), {
height: 60,
}).then((canvas) => {
let imgUrl = canvas.toDataURL('image/png')
const image = document.createElement('img')
image.src = imgUrl
image.style.height = '60px'
image.onload = function () {
const selection = window.getSelection()
if (selection.rangeCount > 0) {
selection.removeAllRanges()
}
if (!document.queryCommandSupported('copy')) {
console.log('浏览器不支持复制命令')
return;
}
const range = document.createRange()
range.selectNode(image)
selection.addRange(range)
document.execCommand('copy')
selection.removeAllRanges()
}
canvasWrap.current.appendChild(image)
})
}
navigator.clipboard
可用但存在浏览器兼容性问题(主流浏览器都已经支持)
const getCanvas = (element) =>x
new Promise((resolve) => {
if (canvasRef.current) {
return resolve(canvasRef.current)
}
html2canvas(element, {
useCORS: true,
}).then((canvas) => {
canvasRef.current = canvas
resolve(canvas)
})
})
const handleCopy2 = async () => {
const canvas = await getCanvas(document.querySelector('.html-canvas'))
canvas.toBlob(async (blob) => {
const data = [
new ClipboardItem({
[blob.type]: blob,
}),
]
navigator.clipboard
.write(data)
.then(() => {
console.log('Copied to clipboard successfully!')
})
.catch(() => {
console.error('Unable to write to clipboard.')
})
})
}
保存图片到本地
const handleSave = async () => {
let canvas = await getCanvas(document.querySelector('.html-canvas'))
const imgUrl = canvas.toDataURL('image/png')
const aEle = document.createElement('a')
aEle.download = 'download'
aEle.href = imgUrl
const event = new MouseEvent('click')
aEle.dispatchEvent(event)
}
|