/**
 * 兼容复制
 */
if (!navigator.clipboard) navigator.clipboard = {};
if (!navigator.clipboard.writeText) navigator.clipboard.writeText = content => new Promise((resolve, reject) => {
    let input = document.createElement("input");
    input.setAttribute("value", content);
    document.body.appendChild(input);
    input.select();
    document.execCommand('copy');
    document.body.removeChild(input);
    resolve();
});

/**
 * 粘贴板
 * @param {string} content 
 */
const clipboard = (content = "") => navigator.clipboard.writeText(content);

/**
 * 新建图片
 * new Image();
 * @param {*} link 
 * @returns 
 */
const newImage = link => new Promise((resolve, reject) => {
    let image = new Image();
    image.src = link;
    image.onload = () => resolve(image);
    image.onerror = error => reject(error);
});

/**
 * 复制图片
 * @param {*} link 
 * @returns 
 */
const copyPicture = link => new Promise((resolve, reject) => {
    let canvas = document.createElement("canvas");
    newImage(link).then(image => {
        canvas.width = image.width;
        canvas.height = image.height;
        let context = canvas.getContext("2d");
        context.drawImage(image, 0, 0);
        canvas.toBlob(blob => navigator.clipboard.write([new ClipboardItem({ [blob.type]: blob })]).then(() => resolve()).catch(error => reject(error)));
    }).catch(error => reject(error));
});

文章作者: CaptainTwo
版权声明: 本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 CaptainTwo
JavaScript JavaScript
喜欢就支持一下吧