我有一个 chrome 扩展,我想创建一个调色板图像并下载它。知道如何解决这个问题吗?基本上,我想将扩展中的数组或颜色转换为图像。 例子: [1d7874,679289,f4c095,ee2e31] 转换为
我正在考虑尝试 html2canvas 或 dom-to-image。
有人有更好的解决方案可以尝试吗?
html2canvas
和dom-to-image
似乎都可以完成这项工作,下面的代码使用dom-to-image
并下载blob
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Color palate drawer</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js"
integrity="sha512-01CJ9/g7e8cUmY0DFTMcUw/ikS799FHiOA0eyHsUWfOetgbx/t6oV4otQ5zXKQyIrQGTHSmRVPIgrgLcZi/WMA=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
></script>
<script defer>
const drawColoredSquares = (colors) => {
const containerDiv = document.createElement("div");
containerDiv.style.display = "inline-flex";
containerDiv.style.flexWrap = "nowrap";
for (const hexColor of colors) {
const div = document.createElement("div");
div.style.width = "168px";
div.style.height = "294px";
div.style.backgroundColor = `#${hexColor}`;
div.style.color = `white`;
div.style.display = "flex";
div.style.justifyContent = "center";
div.style.alignItems = "flex-end";
div.textContent = hexColor;
containerDiv.appendChild(div);
}
return containerDiv;
};
document.addEventListener("DOMContentLoaded", (event) => {
const hexColors = ["1D7874", "679289", "F4C095", "EE2E31"];
const coloredDivContainer = drawColoredSquares(hexColors);
const node = document.body.appendChild(coloredDivContainer); // Elements must be rendered first
domtoimage
.toBlob(node)
.then((blob) => {
node.remove(); // remove rendered element
// Download the blob
const blobUrl = URL.createObjectURL(blob);
var link = window.document.createElement("a");
link.href = blobUrl;
link.download = "palate.png";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
.catch((error) => {
node.remove(); // remove rendered element
console.error("oops, something went wrong!", error);
});
});
</script>
</head>
<body></body>
</html>