900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > JS复制图片到剪切板 读取剪切板

JS复制图片到剪切板 读取剪切板

时间:2019-12-25 18:20:46

相关推荐

JS复制图片到剪切板 读取剪切板

JS复制图片到剪切板 读取剪切板

navigator.clipboard实现复制图片

图片写入剪切板

function handleCopyImg() {const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const img = new Image(); canvas.width = testImg.width; canvas.height = testImg.height; img.crossOrigin = "Anonymous"; img.src = testImg.src; img.onload = () => {ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); ctx.drawImage(img, 0, 0); // 将canvas转为blob canvas.toBlob(async blob => {console.log(blob);const data = [ new ClipboardItem({[blob.type]: blob, }),];// https://w3c.github.io/clipboard-apis/#dom-clipboard-writeawait navigator.clipboard.write(data) .then(() => {console.log("Copied to clipboard successfully!");},() => {console.error("Unable to write to clipboard.");});}); }}btn.addEventListener("click", handleCopyImg, false);

read方法返回一个Promise,可获取复制的内容

async function foo() {const items = await navigator.clipboard.read(); const imageBlob = await items[0].getType("image/png"); console.log("imageBlob==>", imageBlob);}// 读取文本async function foo() {await navigator.clipboard.readText().then((data) => {console.log(data);});}

write方法,写入剪切板内容,如图片或其它文件等

const data = [new ClipboardItem({"text/plain": new Blob(["hello clipboard"], {type: "text/plain" })})];navigator.clipboard.write(data).then(() => {console.log("Copied to clipboard successfully!");},() => {console.error("Unable to write to clipboard. :-(");});// writeText方法写入文本内容navigator.clipboard.writeText("hello!!!");

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。