As shown in the above picture there are 2 steps.
1. Get SVG on HTML5 canvas
2. Convert Canvas to PNG image
Get SVG on HTML5 canvas
// get Canvas Element var myCanvas = document.getElementById('canvasid'); // get 2D context var myCanvasContext = myCanvas.getContext('2d'); // Load up our image. var source = new Image(); source.src = '/img/twitter.svg'; // Render our SVG image to the canvas once it loads. source.onload = function(){ myCanvasContext.drawImage(source,0,0,200,200); }
Convert Canvas to PNG image
$("#resultImage").attr("src",myCanvas.toDataURL("image/png"));Completed code:
<!DOCTYPE html> <html> <head> <title>SVG to PNG conversion using HTML5 Canvas - DEMO</title> <script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script> <style> td { padding:20px; text-align:center; } h1 { color:#555; } </style> </head> <body> <div style="width:720px;margin:auto;"> <table> <tr> <td> <h1>SVG</h1> <img width="200" height="200" src="/img/twitter.svg"/> </td> <td> <h1>HTML5 Canvas</h1> <canvas id="cancan" width="200" height="200">Canvas Blue Goat</canvas> </td> <td> <h1>PNG Image</h1> <img id="resultImage"/> </td> </tr> </table> </div> <script> $(function(){ var myCanvas = document.getElementById('cancan'); var myCanvasContext = myCanvas.getContext('2d'); // Load up our image. var source = new Image(); source.src = '/img/twitter.svg'; // Render our SVG image to the canvas once it loads. source.onload = function(){ myCanvasContext.drawImage(source,0,0,200,200); $("#resultImage").attr("src",myCanvas.toDataURL("image/png")); } }); </script> </body> </html>Source URL: http://blog.sodhanalibrary.com/2014/04/svg-to-png-conversion-using-html5-canvas.html
0 comments:
Post a Comment