应该发生什么:
照常复制图像。当您按下按钮时 - 图像被放置在 div 内(当它成为背景时,它会变成不同的大小)。单击 div 时,它将图像写回剪贴板,可以粘贴(假设您同时复制了其他内容),尺寸与 oringal 相同。
实际发生了什么:
新粘贴的图像/剪贴板设置了它自己的尺寸,尽管给出了它应该遵循的尺寸。
代码:
export async function run() {
// Try to access clipboard data using the Clipboard API
const images = await navigator.clipboard.read();
const image = images[0];
if (image.types[0] === "image/png" || image.types[0] === "image/jpg") {
// Load the image using the ImageBitmap API to get its dimensions
const bitmap = await createImageBitmap(await image.getType("image/png"));
const width = bitmap.width;
const height = bitmap.height;
// Now you have access to the width and height of the image
console.log("Image width:", width);
console.log("Image height:", height);
insertImage(image, width, height);
}
}
//THIS WORKS BUT WRONG SIZE//
async function insertImage(clipboardItem, height, width) {
clipboardItem.getType("image/png").then(async (blob) => {
if (blob) {
const imageUrl = URL.createObjectURL(blob);
const hereDiv = document.querySelector(".here");
hereDiv.style.backgroundImage = `url('${imageUrl}')`;
hereDiv.style.backgroundSize = "cover";
hereDiv.style.backgroundRepeat = "no-repeat";
hereDiv.style.backgroundPosition = "center";
// Attach the click event listener to the div after the image is inserted
hereDiv.addEventListener("click", async () => {
// Read the background image directly from the div and copy it to the clipboard
const backgroundImage = window.getComputedStyle(hereDiv).backgroundImage;
if (backgroundImage && backgroundImage !== "none") {
const imageUrl = backgroundImage.slice(4, -1).replace(/['"]/g, "");
fetch(imageUrl)
.then((response) => response.blob())
.then((blob) => {
const clipboardItem = new ClipboardItem({ "image/png": blob }, { "image/png": blob });
clipboardItem.imageWidth = width;
clipboardItem.imageHeight = height;
console.log(clipboardItem);
navigator.clipboard.write([clipboardItem]);
const images = navigator.clipboard.read();
console.log(images);
})
.catch((error) => {
console.error("Error copying image to clipboard:", error);
});
} else {
console.log("No image available to copy.");
}
});
}
});
}