JS复制JPG图片到剪切板

HTML代码:
<button id="button" type="primary" class="ui-button">复制JPG图片</button>
<img id="image" width="150" src="./mybook.jpg">
JS代码:
const doCopyImg2Clipboard = async (image, success = () => {}, failure = () => {}) => {
    if (!image || !image.src) {
        return;    
    }
    
    // 原图尺寸
    const { naturalWidth, naturalHeight } = image;
    
    if (!naturalWidth) {
        failure('图片尚未成功加载');
        
        return;
    }
    
    // 绘制图片到canvas上
    const canvas = document.createElement('canvas');
    canvas.width = naturalWidth;
    canvas.height = naturalHeight;
    // canvas绘制上下文
    const context = canvas.getContext('2d');
    // 图片绘制
    context.drawImage(image, 0, 0, naturalWidth, naturalHeight);
    // 转为Blob数据
    canvas.toBlob(blob => {
        // 使用剪切板API进行复制
        const data = [new ClipboardItem({
            ['image/png']: blob    
        })];
        
        navigator.clipboard.write(data).then(success, failure);
    });
}
// 点击按钮进行复制 button.addEventListener('click', () => { doCopyImg2Clipboard(image, function () { new LightTip('复制成功', 'success'); }, function (err) { new LightTip('复制失败:' + err, 'error'); }); }); 
 
posted @ 2024-01-24 17:44  干饭吧  阅读(258)  评论(0)    收藏  举报