如果我不在html中添加 foreignObject 标记,代码工作正常并且内容保存为图像文件但是当我添加foreignObject时,浏览器在控制台中显示错误。如果SVG包含foreignObject,有没有办法将SVG转换为canvas并将其保存到图像文件。我试过的代码在
下面<button id="button">svg to png</button>
<svg id = "svgId" width="13cm" height="13cm" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="200" height="200">
<rect x="0" y="0" width="5cm" height="5cm" style="fill:red;"/>
<g>
<rect width = "8.6cm" height = "10cm" style="stroke:black; stroke-width:2; fill:none;"/>
<text x="1cm" y = "6.5cm" style="font-size:28px;">Heading Here</text>
<line x1="0cm" y1="8cm" x2="8.6cm" y2="8cm" style="stroke:black; stroke-width:1;"/>
<foreignObject width="8cm" height="4.5cm" x = "0.5cm" y="8.5cm" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<p xmlns="http://www.w3.org/1999/xhtml" id = "news1">Text goes here asd sadl sad sadsad sad sa dsad asd sad saasd sad asd sad sad sasd sadsa dsa sadsad sad asdjsalkdjsal salkdj jsalkdjsal akld lksa adsad asa asa sa adasdas das dsad sad sad asd sad sad sakldjsalkjdlsakdj sakldj salkdjsakldjsaldkja sdlksaj dlkaj sa</p>
</foreignObject>
</g>
</svg>
<canvas id="canvas" width="400" height = "400"></canvas>
<script type="text/javascript">
var btn = document.getElementById('button');
var svg = document.getElementById('svgId');
var canvas = document.getElementById('canvas');
function triggerDownload (imgURI) {
var evt = new MouseEvent('click', {
view: window,
bubbles: false,
cancelable: true
});
var a = document.createElement('a');
a.setAttribute('download', 'image.png');
a.setAttribute('href', imgURI);
a.setAttribute('target', '_blank');
a.dispatchEvent(evt);
}
btn.addEventListener('click', function () {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var data = (new XMLSerializer()).serializeToString(svg);
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,'12cm','12cm');
DOMURL.revokeObjectURL(url);
var imgURI = canvas
.toDataURL('image/png')
.replace('image/png', 'image/octet-stream');
triggerDownload(imgURI);
};
img.src = url;
});
</script>