【发布时间】:2022-01-04 20:21:51
【问题描述】:
铬:v96 火狐:v95
我正在尝试从浏览器下载 SVG 图像作为 PNG 图像。这似乎适用于 Chrome,但我正在使用 Firefox 下载空白图像。知道为什么吗?
export function downloadSvgImage(svgElement: HTMLElement, name: string) {
const xml = new XMLSerializer().serializeToString(svgElement);
const svg64 = window.btoa(xml);
const b64Start = 'data:image/svg+xml;base64,';
const viewBox = svgElement.getAttribute('viewBox');
const dimensionArr = viewBox.split(' ');
const width = parseInt(dimensionArr[2]);
const height = parseInt(dimensionArr[3]);
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
const image = new Image();
image.onload = () => {
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
canvas.toBlob((blob: any) => {
const anchor = document.createElement('a');
anchor.download = `${name}.png`;
anchor.href = URL.createObjectURL(blob);
anchor.click();
URL.revokeObjectURL(blob);
}, 'image/png');
};
image.src = b64Start + svg64;
}
【问题讨论】:
-
developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/… 文档说如果发生错误,blob 可以为空。是这样吗?
-
当我在 .toBlob 函数中 console.log() 时,blob 不为空。 Firefox 中 blob 的大小,比 Chrome 中的 blob 小很多。
-
我很好奇如果您不调用 revokeObjectURL 是否会得到不同的结果 - 我想知道这里是否存在竞争条件。
-
这是个好主意,但是当我不调用revokeObjectURL时,它仍然不起作用。
标签: javascript html typescript svg html5-canvas