我正在使用下面的代碼從有效的 svg 字串創建一個 png。svg 中有一個嵌入的影像。
<image xlink:href="data:image/png;base64,..." x="0" y="0" width="362" height="234"/>
這在 chrome 和 firefox 中運行良好,但我在 safari 和 safari mobile 中出現了這種奇怪的行為。嵌入的影像有時是空白的。布局仍然尊重影像的尺寸,但呈現為空白。svg 的其余部分仍然可以很好地呈現。

let canvas = document.createElement('canvas')
let ctx = canvas.getContext('2d')
canvas.width = width
canvas.height = height
ctx.fillStyle = 'white'
ctx.fillRect(0, 0, width, height)
let img = new Image()
img.onload = function () {
ctx.drawImage(img, 0, 0, width, height, padding, 0, width, height)
canvas.toBlob((blob) => {
saveAs(blob, 'image.png')
})
}
img.src = URL.createObjectURL(new Blob([rawSvgString], { type: 'image/svg xml' }))
uj5u.com熱心網友回復:
這是一個已知的老錯誤。
對于解決方法,似乎一個簡單的setTimeout(draw, 100)就足夠了,盡管老實說這似乎很脆弱(例如0,使用我的影像而不是錯誤報告中的字體示例)。
const ctx = document.querySelector("canvas").getContext("2d");
(async () => {
const png_blob = await fetch("https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png").then(r=>r.ok&&r.blob());
const png_dataURL = await readAsDataURL(png_blob);
const anti_cache = "#" Math.random();
const svg_markup = `<svg xmlns="http://www.w3.org/2000/svg" width="300" height="150" viewBox="0 0 100 100">
<rect width="10" height="10" fill="purple"/>
<image href="${ png_dataURL anti_cache }" width="100" height="100"/>
</svg>`;
const svg_blob = new Blob([svg_markup], { type: "image/svg xml" });
const img = new Image();
img.src = URL.createObjectURL(svg_blob);
img.onload = (evt) => {
setTimeout(
() => ctx.drawImage(img, 0, 0),
100
);
};
})().catch(console.error);
function readAsDataURL(blob) {
const reader = new FileReader();
return new Promise((res, rej) => {
reader.onload = () => res(reader.result);
reader.onerror = rej;
try {
reader.readAsDataURL(blob);
}
catch(err) {
rej(err);
}
});
}
<canvas></canvas>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/332684.html
標籤:javascript html svg 帆布 苹果浏览器
