Is it possible to copy a canvas image to the clipboard?

前端 未结 4 644
难免孤独
难免孤独 2020-12-20 13:17

I\'ve created an image from my canvas object by using canvas.toDataURL(\"image/png\", 0.7). It works fine to save the image from the context menu but it doesn\'

4条回答
  •  鱼传尺愫
    2020-12-20 13:32

    Clipboard API for images are now available on chrome

    https://github.com/web-platform-tests/wpt/tree/master/clipboard-apis

    const item = new ClipboardItem({ "image/png": blob });
    navigator.clipboard.write([item]); 
    

    Example

    const canvas = document.createElement("canvas");
    canvas.width = 100;
    canvas.height = 100;
    document.body.appendChild(canvas);
    const ctx = canvas.getContext("2d");
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = "#eee";
    ctx.fillRect(10, 10, 50, 50);
    
    //tested on chrome 76
    canvas.toBlob(function(blob) { 
        const item = new ClipboardItem({ "image/png": blob });
        navigator.clipboard.write([item]); 
    });
    

提交回复
热议问题