Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clipboard.write() - log and fixes #33769

Merged
merged 2 commits into from
May 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 26 additions & 3 deletions files/en-us/web/api/clipboard/write/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,27 @@ The HTML just defines our `<canvas>` element and the `<div>` element with id `ta
<div id="target">Paste here.</div>
```

```html hidden
<pre id="log"></pre>
```

```css hidden
#log {
height: 60px;
overflow: scroll;
padding: 0.5rem;
border: 1px solid black;
}
```

```js
const logElement = document.querySelector("#log");
function log(text) {
logElement.innerText = `${logElement.innerText}${text}\n`;
logElement.scrollTop = logElement.scrollHeight;
}
```

#### JavaScript

First we define an `async` function to copy a canvas to a blob.
Expand Down Expand Up @@ -131,11 +152,12 @@ async function copyCanvasContentsToClipboard() {
const data = [new ClipboardItem({ [blob.type]: blob })];
// Write the data to the clipboard
await navigator.clipboard.write(data);
log("Copied");
} catch (error) {
console.log(error);
log(error);
}
} else {
console.log("image/png is not supported");
log("image/png is not supported");
}
}
```
Expand Down Expand Up @@ -173,14 +195,15 @@ body {
}
img {
margin: 0.5rem;
}
```

#### Result

The result is shown below.
First click on the blue square, and then select the text "Paste here" and use your OS-specific keyboard combinatations to paste from the clipboard (such as `Ctrl+V` on Windows).

{{embedlivesample("write_canvas_contents_to_the_clipboard", "", "300")}}
{{embedlivesample("write_canvas_contents_to_the_clipboard", "", "400")}}

## Specifications

Expand Down