如何解决Javascript canvas.toDataUrl()在Firefox中无法正确编码?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (424)

转换代码和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);
    }

});
}
提问于
用户回答回答于

在使用之前设置heightand width属性XMLSerializer:

sourceSVG.setAttribute('width', 500);
sourceSVG.setAttribute('height', 500);
用户回答回答于

试试以下代码:

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>

扫码关注云+社区

领取腾讯云代金券