copyClipboardImage
A function that reads an image from the given image source and saves it to the Clipboard.
navigator.clipboard.write is not supported in some browsers. If write is not supported, clipboardTextCopy is called instead.
In Chrome, the write() function of the Clipboard API only supports text/plain, text/html, and image/png formats. Therefore, image formats such as jp(e)g and webp cannot generally be copied to the clipboard.
copyClipboardImage automatically converts image formats not supported by the write() function to png before saving them to the clipboard.
For image types like image/svg+xml where the source code can be copied and used, the toText option is provided as an optional parameter. When toText is true, clipboardTextCopy is called.
- See the example below for reference.
Code
Interface
typescript
function copyClipboardImage(
src: string,
options?: {
toText: boolean;
}
): Promise<Blob | string>;
Usage
Basic Usage
typescript
import { copyClipboardImage } from '@modern-kit/utils';
import img from './assets/react.png';
// Image src to copy (png, jp(e)g, webp)
const result = await copyClipboardImage(img); // result: Blob
Using the toText Option
typescript
import { copyClipboardImage } from '@modern-kit/utils';
import svg from './assets/react.svg';
const result = await copyClipboardImage(svg, { toText: true }); // result type: string
/* Clipboard copy result: text()
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-11.5 -10.23174 23 20.46348">
<title>React Logo</title>
<circle cx="0" cy="0" r="2.05" fill="#61dafb"/>
<g stroke="#61dafb" stroke-width="1" fill="none">
<ellipse rx="11" ry="4.2"/>
<ellipse rx="11" ry="4.2" transform="rotate(60)"/>
<ellipse rx="11" ry="4.2" transform="rotate(120)"/>
</g>
</svg>
*/