Skip to content

Instantly share code, notes, and snippets.

@christophervigliotti
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christophervigliotti/682753c2db483659fe7d to your computer and use it in GitHub Desktop.
Save christophervigliotti/682753c2db483659fe7d to your computer and use it in GitHub Desktop.
Convert An SVG To Canvas (And Then To PNG)
<!DOCTYPE html>
<html>
<head>
<title>SVG > Canvas</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/canvg.js"></script>
<script src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js"></script>
<script src="http://canvg.googlecode.com/svn/trunk/StackBlur.js"></script>
<script type="text/javascript">
var doConvertSvgToCanvas = function(){
console.log('step 1, convert from svg to canvas');
// get the svg
var svgString = $('#svgContainer').html();
svgString = svgString.replace(/^\s+|\s+$/g,''); // canvg() does not like whitespace before the start of the svg tag
// call canvg (awesome)
canvg(document.getElementById('theCanvas'), svgString, {renderCallback: onConvertSvgToCanvas});
};
var onConvertSvgToCanvas = function(){
console.log('step 2, convert from canvas to png, then draw to screen');
var canvas = document.getElementById('theCanvas');
var image = new Image();
image.id = 'pic';
image.src = canvas.toDataURL();
$('#thePng').attr('src',image.src);
};
jQuery( document ).ready(function( $ ) {
doConvertSvgToCanvas();
});
</script>
</head>
<body>
<h1>The SVG</h1>
<div id="svgContainer">
<svg>
<rect x="20" y="50" width="100" height="50" fill="yellow" stroke="navy" stroke-width="5"/>
<rect x="150" y="50" width="100" height="50" rx="10" fill="green"/>
</svg>
</div>
<h1>The Canvas</h1>
<canvas id="theCanvas"></canvas>
<h1>The PNG</h1>
<img id="thePng" />
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment