
b64-to-blob、html2canvas
具体方式过html2canvas,就可以获取完整的dom节点,再通过b64-to-blob,将base64格式转换成blob,将blob赋值到浏览器剪切板就大功告成了
复制功能代码const copy = () => {
html2canvas(imgRef.current, {
useCORS: true
}).then((canvas) => {
const imgUrl = canvas.toDataURL('image/png');
const str = imgUrl.replace(/data:image\/png;base64,/, '');
const file = b64toBlob(str, 'image/png');
const clipboardItemInput = new window.ClipboardItem({ 'image/png': file });
window.navigator.clipboard.write([clipboardItemInput]);
});
};
完整代码
import React, { useState, useEffect, useRef } from 'react';
import html2canvas from 'html2canvas';
import b64toBlob from 'b64-to-blob';
import bg from 'public/1.png';
const CopyImg= (props) => {
const imgRef= useRef();
const copy = () => {
html2canvas(imgRef.current, {
useCORS: true
}).then((canvas) => {
const imgUrl = canvas.toDataURL('image/png');
const str = imgUrl.replace(/data:image\/png;base64,/, '');
const file = b64toBlob(str, 'image/png');
const clipboardItemInput = new window.ClipboardItem({ 'image/png': file });
// 这里 window.navigator.clipboard在谷歌浏览器中,只有安全网络环境才能访问,https/localhost可以,http是访问不到的
window.navigator.clipboard.write([clipboardItemInput]);
});
};
useEffect(() => {
init();
}, []);
return (
<div>
<button onClick={() => copy()}>复制图片 </button>
<img ref={imgRef} src={bg} alt="" />
</div>
);
};
export default CopyImg;
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)