当前位置:网站首页>JS复制图片到剪切板 读取剪切板

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

2022-07-07 05:05:00 qiphon3650

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-write 
		await 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!!!");

原网站

版权声明
本文为[qiphon3650]所创,转载请带上原文链接,感谢
https://qiphon.blog.csdn.net/article/details/125644697