Skip to content

Instantly share code, notes, and snippets.

@romannurik
Created September 2, 2010 00:39
Show Gist options
  • Save romannurik/561635 to your computer and use it in GitHub Desktop.
Save romannurik/561635 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>SVG/Canvas/toDataURL bug</title>
<script src="http://javascriptbase64.googlecode.com/svn/trunk/base64.js"></script>
<style>
img { border: 3px solid red; }
canvas { border: 3px solid blue; }
</style>
</head>
<body>
<textarea id="svg-source" style="width: 100%;" rows="9"></textarea>
<button>Go</button>
<div id="out"></div>
<script>
document.getElementById('svg-source').value = (
'<?xml version="1.0" encoding="utf-8"?>\n' +
'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' +
'<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"\n' +
'width="48px" height="48px" viewBox="0 0 48 48" enable-background="new 0 0 48 48" xml:space="preserve">\n' +
'<g><path fill-rule="evenodd" clip-rule="evenodd" d="M24,7.957c-5.909,0-10.699,4.79-10.699,10.699c0,2.537,0.883,4.868,2.359,6.702\n' +
'c1.791,2.227,5.646,4.232,6.412,13.074c0,0.518,0.322,1.611,1.928,1.611s1.957-1.094,1.957-1.611\n' +
'c0.765-8.842,4.592-10.848,6.383-13.074c1.476-1.833,2.359-4.165,2.359-6.702C34.699,12.747,29.908,7.957,24,7.957z M23.833,22.131\n' +
'c-1.911,0-3.46-1.549-3.46-3.46c0-1.91,1.549-3.459,3.46-3.459s3.46,1.549,3.46,3.459C27.293,20.583,25.744,22.131,23.833,22.131z"/>\n' +
'</g></svg>');
var out = document.getElementById('out');
function log(txt) {
out.innerHTML += '<div>' + txt + '</div>';
}
document.getElementsByTagName('button')[0].addEventListener('click', function(evt) {
var dataUrl = 'data:image/svg+xml;base64,' + Base64.encode(document.getElementById('svg-source').value);
out.innerHTML = '';
var img = document.createElement('img');
var canvas = document.createElement('canvas');
img.onerror = function() {
log('SVG parse error');
};
img.onload = function() {
log('&lt;img&gt; with SVG src loaded successfully');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
log('drawImage() of &lt;img&gt; into &lt;canvas&gt; successful');
log('Attempting &lt;canvas&gt; toDataURL');
try {
log('Canvas toDataURL result: ' + canvas.toDataURL());
} catch (e) {
log('<span style="color:red">' + e + '</span>');
}
out.appendChild(img);
out.appendChild(canvas);
};
img.src = dataUrl;
}, false);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment