export async function copyPNGs() {
const svgElements = document.getElementsByClassName("highcharts-root");
const gutterSpacing = 15;
const width = 650;
const height = 400;
const background = "#eee";
// Create a temporary canvas element to render the SVGs as PNGs
const canvas = document.createElement("canvas");
canvas.width = width * 2 + gutterSpacing * 3;
canvas.height = (height + gutterSpacing) * Math.ceil(svgElements.length / 2) + gutterSpacing;
const context = canvas.getContext("2d");
// Fill the canvas with a light gray background color.
if (context) {
context.fillStyle = background;
context.fillRect(0, 0, canvas.width, canvas.height);
}
// Render each SVG as a PNG and draw it on the canvas.
for (let i = 0; i < svgElements.length; i++) {
const row = Math.ceil((i + 1) / 2) - 1;
const column = i % 2;
const svg = svgElements[i];
const svgData = new XMLSerializer().serializeToString(svg);
const img = new Image();
const isEven = column === 0;
img.onload = function () {
const dx = column * width + (!isEven ? gutterSpacing : 0) + gutterSpacing;
const dy = row * height + (row !== 0 ? gutterSpacing * row : 0) + gutterSpacing;
context?.drawImage(img, dx, dy, width, height);
};
// Convert the SVG to a data URL and set the src of the image element to it.
img.src = "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(svgData)));
}
// Wait for a second to make sure all images are loaded, then convert the canvas to a blob and copy it to the clipboard.
setTimeout(() => {
canvas.toBlob(async (blob) => {
if (blob === null) {
alert("Could not copy the charts");
} else {
await navigator.clipboard.write([new ClipboardItem({ "image/png": blob })]);
}
}, "image/png");
}, 1000);
}
1条答案
按热度按时间gijlo24d1#
下面的示例将获取所有SVG,在本例中,它们都可以从className highcharts-root中选择。
然后创建一个画布,循环SVG,转换成PNG并添加到画布上,最后将画布复制到剪贴板上。
可以改进的一个部分是在结束时强制超时,以确保所有图像都已加载到画布上。
此版本还将在网格2中粘贴X网格中的图像,如下所示:
| 图像|图像|
| - ------|- ------|
| 图像|图像|
| 图像|图像|
| 图像|图像|
这可以根据需要进行调整。