JavaScript复制图片和下载图片到本地

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

经测试在大多数社交工具中粘贴不可用

 // 实现 handleCopy 方法
 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

可用但存在浏览器兼容性问题,主流浏览器中firefox和Safari兼容性不好

 // 实现handleCopy2 方法
 const getCanvas = (element) =>
   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.')
		})
	})
}
保存图片到本地
 // 实现 handleSave 方法
 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)
 }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值