无法将SVG中的图像转换为图片

时间:2018-06-25 03:46:36

标签: javascript html image svg canvas

您好,我正在尝试将svg转换为png,基本思想是先将svg转换为canvas,然后将画布另存为png。但是,svg内部的图像元素无法转换。代码如下:

var testBtn = document.getElementById("testBtn");
	var testSVG = document.getElementById('testSVG');
	var testCanvas = document.getElementById('orgChartCanvas');

	function triggerDownload (imgURI) {
	  var evt = new MouseEvent('click', {
	    view: window,
	    bubbles: false,
	    cancelable: true
	  });

	  var a = document.createElement('a');
	  a.setAttribute('download', 'MY_COOL_IMAGE.png');
	  a.setAttribute('href', imgURI);
	  a.setAttribute('target', '_blank');

	  a.dispatchEvent(evt);
	}

	testBtn.addEventListener('click', function () {
	  var canvas = document.getElementById('orgChartCanvas');
	  var ctx = canvas.getContext('2d');
	  var data = (new XMLSerializer()).serializeToString(testSVG);
	  var DOMURL = window.URL || window.webkitURL || window;

	  var img = new Image();
	  var svgBlob = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
	  var url = DOMURL.createObjectURL(svgBlob);

	  img.onload = function () {
	    ctx.drawImage(img, 0, 0,2000,800);
	    DOMURL.revokeObjectURL(url);

	    var imgURI = canvas
	        .toDataURL('image/png')
	        .replace('image/png', 'image/octet-stream');

	    triggerDownload(imgURI);
	  };

	  img.src = url;
	});
<button id = "testBtn">svg to png</button>

<svg xmlns="http://www.w3.org/2000/svg" id = "testSVG" viewBox="0 0 1367.25 800">
    <g transform="translate(518.625,20)">
        <text style="font-size: xx-large;">Text is converted!</text>
		<image  xlink:href="https://mdn.mozillademos.org/files/5397/rhino.jpg"></image>
	</g>
</svg>

<canvas id="orgChartCanvas" width="2000" height="1000"></canvas>

那么我还能将svg中的图像转换为png吗?预先感谢!

0 个答案:

没有答案