Drawing SVG Image to Canvas showing up blank
I have an SVG tag. Upon clicking of a button a dynamically create an SVG Image inside the SVG tag.
var svgimg = document.createElementNS('http://www.w3.org/2000/svg','image');
svgimg.setAttributeNS(null,'height','450');
svgimg.setAttributeNS(null,'width','845');
svgimg.setAttribute('class', 'dragImage');
svgimg.addEventListener("mousedown", dragFunc);
svgimg.setAttributeNS('http://www.w3.org/1999/xlink','href', '/images/dog.jpg');
$('#svg').append(svgimg);
Works beautifully. Then, with the click of a different button, I am taking that SVG, and converting it to a Canvas.
var svgContent= document.querySelector('svg').innerHTML;
var img = new Image();
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
img.onload = function(){
context.drawImage(img, 0, 0);
}
img.src = "data:image/svg+xml;base64,"+btoa(svgContent);
However, this shows up blank, empty. No image. If i manually set the img.src to
img.src = "images/dog.jpg";
This will work fine and write to my Canvas. Im guessing it has something to do with the SVG Image type? Here is the HTML:
<div id="parentDiv">
<svg id='svg' width="845" height="450" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink= "http://www.w3.org/1999/xlink"></svg>
</div>
<canvas id="canvas" width="1000px" height="600px"></canvas>
Any help would be great. Essentially, I want to know, why the newly created Image for my Canvas would draw the 'data:image/svg+xml;base64', Am i converting something wrong?
我解决了以下问题:
var svg = document.getElementsByTagName('svg')[0];
var svg_xml = (new XMLSerializer()).serializeToString(svg);
svg.remove();
// write serialized svg to canvas
canvg('canvas', svg_xml, {useCORS: true});
// create canvas data on demand
function downloadCanvas() {
this.href = canvas.toDataURL('image/png');
};
document.getElementById('imgId').addEventListener('click', downloadCanvas, false);
链接地址: http://www.djcxy.com/p/47048.html
上一篇: 在浏览器中显示不同的MIME类型
下一篇: 将SVG图像拖到画布上显示空白