我在通过画布将svg blob转换为png时遇到了问题。
这是我的代码:
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const data = (new XMLSerializer()).serializeToString(svg);
const svgBlob = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
console.log(svgBlob, canvas);
const img = new Image();
const url = URL.createObjectURL(svgBlob);
img.onload = (() => function () {
console.log('inside onload');
ctx.canvas.width = size;
ctx.canvas.height = size;
ctx.drawImage(img, 0, 0);
URL.revokeObjectURL(url);
const imgURI = canvas
.toDataURL('image/png')
.replace('image/png', 'image/octet-stream');
DownloadModalComponent.triggerDownload(imgURI);
});
img.src = url;
console.log(img.complete, img.currentSrc);
之前使用普通的javascript(以及一些jquery)。
控制台正在输出img.complete false并且currentSrc为空。
在网络标签中,我可以看到已获取本地svg网址。
答案 0 :(得分:0)
let svgSource = "yourSVGcodehere"; // string of your <svg></svg>
let data = "data:image/svg+xml," + encodeURIComponent(svgSource);
let ctx = my2dcanvas.getContext("2d"); // my2dcanvas is your canvas element
let img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
my2dcanvas.toBlob(function(blob) {
doSomethingWithBlob(blob) // funciton processing the blob
// clear canvas context:
ctx.clearRect(0, 0, 320, 320)
}, 'image/png');
};
img.src = data;
这是一个刺激工作片段。如果有帮助,请告诉我