为什么当我使用canvg即抛出异常Security错误?

时间:2018-07-26 15:21:16

标签: javascript internet-explorer canvas canvg

我有此代码,但是当我尝试使用canvas.toDataUrl时,IE 11中出现“安全错误”异常,我该如何解决此问题?

var svg = document.querySelector("svg");//get svg
var img = document.createElement("img");//create img
var canvas = document.createElement("canvas");//create canvas

var svgSize = svg.getBoundingClientRect();//get bounds
canvas.width = svgSize.width * 3;
canvas.height = svgSize.height * 3;
canvas.style.width = svgSize.width;
canvas.style.height = svgSize.height;

var svgData = new XMLSerializer().serializeToString(svg);

var svg64 = btoa(svgData);
var b64Start = 'data:image/svg+xml;base64,';
var image64 = b64Start + svg64;

img.onload = function () {
    var ctx = canvas.getContext("2d");
    ctx.scale(3, 3);
    var x0 = Math.floor(0);
    var y0 = Math.floor(0);
    ctx.translate(-x0, -y0);           
    var bg = graph.background;
    //set background
    if (bg == null || bg == '' || bg == mxConstants.NONE) {
        bg = '#ffffff';
    }

    ctx.save();
    ctx.fillStyle = bg;
    ctx.fillRect(x0, y0, Math.ceil(svgSize.width * 3)Math.ceil(svgSize.height * 3));
    ctx.restore();
    ctx.drawImage(img, 0, 0,canvas.width,canvas.height);
    var canvasdata = canvas.toDataURL("image/png", 1);//try to get url for image
    var a = document.createElement("a");
    a.download = "download_img" + ".png";
    a.href = canvasdata;
    document.body.appendChild(a);
    //download my image
    a.click();
};
img.src = image64;//set src

在Chrome中工作正常,但是在我遇到一些问题时,请帮助我。

更新

如果我使用canvg,则toDataUrl返回空白图像  这是我更改的代码

            var svg = document.querySelector('svg');
            var canvas = document.createElement('canvas');

            var svgSize = svg.getBoundingClientRect();
            canvas.width = svgSize.width * 3;
            canvas.height = svgSize.height * 3;
            canvas.style.width = svgSize.width;
            canvas.style.height = svgSize.height;
            svg.width = svg.parentNode.width;
            svg.height = svg.parentNode.height;
            var svgData = new XMLSerializer().serializeToString(svg);   
            canvg(canvas, svgData.trim());
            var dataURL = canvas.toDataURL('image/png');
            var data = atob(dataURL.substring('data:image/png;base64,'.length)),
                asArray = new Uint8Array(data.length);

            for (var i = 0, len = data.length; i < len; ++i) {
                asArray[i] = data.charCodeAt(i);
            }

            var blob = new Blob([asArray.buffer], { type: 'image/png' });
            saveAs(blob, 'export_' + Date.now() + '.png');

我在页面上有这个svg

我也只有svg。 结果我想保存这个 image

0 个答案:

没有答案