我正在尝试获取SVG并将其转换为image/png
数据URL。
在Chrome 68中,它可以完美运行,但在Firefox 61中,它使用以下网址呈现空白图片:
数据:图像/ PNG; BASE64,iVBORw0KGgoAAAANSUhEUgAAAUAAAAFACAYAAADNkKWqAAABpElEQVR4nO3BAQ0AAADCoPdPbQ8HFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMCnAUGaAAH3lkeeAAAAAElFTkSuQmCC
下面找到我要转换和SVG的代码。您可能会意识到,这几乎只是从其他人试图完成此操作的不同站点/问题中复制/粘贴。
function importSVG(sourceSVG, height = null, width = null) {
return new Promise(function (resolve, reject) {
try {
// https://developer.mozilla.org/en/XMLSerializer
const svgString = (new XMLSerializer()).serializeToString(sourceSVG);
let svgSize = sourceSVG.getBoundingClientRect();
let canvas = document.getElementById('compass-canvas');
canvas.width = width ? width : svgSize.width;
canvas.height = height ? height : svgSize.height;
let ctx = canvas.getContext('2d');
let img = document.createElement('img');
let svg = new Blob([svgString], {type: 'image/svg+xml;charset=utf-8'});
let DOMURL = self.URL || self.webkitURL || self;
let url = DOMURL.createObjectURL(svg);
img.onload = (function () {
ctx.drawImage(img, 0, 0);
let png = canvas.toDataURL();
DOMURL.revokeObjectURL(png);
resolve({image: png});
});
img.onerror =
img.onabort = function (e) {
console.error('generateIcon : error on image', e);
};
img.src = url;
}
catch (e) {
console.log('reject', e);
reject(e);
}
});
}
这是其他人在较新的Firefox中遇到的一个问题,还是我缺少一些应该很明显的东西?
答案 0 :(得分:0)
对我来说很好(我确实简化了您的代码以使其更适合代码段):
var svgString = '<svg id="test" width="200px" height="30px" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <g xmlns="http://www.w3.org/2000/svg"> <rect fill="#67b7dc" transform="translate(-0.5,-0.5)" width="300" height="50" /> <text fill="#fff" font-size="25" dy="20"> <tspan> Some text</tspan> </text> </g></svg>'
let canvas = document.getElementById('compass-canvas');
canvas.width = 200
canvas.height = 50
let ctx = canvas.getContext('2d');
let img = document.createElement('img');
let svg = new Blob([svgString], {
type: 'image/svg+xml;charset=utf-8'
});
let DOMURL = self.URL || self.webkitURL || self;
let url = DOMURL.createObjectURL(svg);
img.onload = (function() {
ctx.drawImage(img, 0, 0);
});
img.src = url;
<canvas id='compass-canvas'></canvas>
与您的代码唯一的不同是,我确实对SVG图像进行了硬编码以进行测试...
仔细检查sourceSVG中的内容,以确保是有效的SVG
答案 1 :(得分:0)
正如@HelderSepu所说,我的代码没有错。 firefox的问题是我没有在SVG元素上设置高度/宽度。
我在@Kaiido的答案here
中找到了解决方案因此,在使用height
之前,我先设置了width
和XMLSerializer
属性:
sourceSVG.setAttribute('width', 500);
sourceSVG.setAttribute('height', 500);