Maintain Font coverting SVG to Canvas
If you notice your font has tranformed to Times when turning a SVG into a canvas, this will demonstrate how to protect that font.
HTML
<p style="font-size:12px">Since one can't right click and save an SVG based data viz as a png, the SVG needs to be converted to an image first and secondly a canvas if cropping is required and then back to an image. The library <a href="https://github.com/hongru/canvas2image">canvas2Image</a> is excellent for such juggling.</p>
<p style="font-size:12px">I discovered that my font went missing and was replaced by Times New Roman during the process of converting a SVG to an img. After some research, <a href=' http://graphicdesign.stackexchange.com/questions/5162/how-do-i-embed-google-web-fonts-into-an-svg'>this article</a> explained that the font needs to be base64 encoded and I found that <a href=' http://www.fontsquirrel.com/tools/webfont-generator'>fontsquirrel.com</a> offers this as "Expert" feature that you need to enable. You'll notice that the text in the img is much more crisp [identical to the svg!] than the canvas which is a sad reality of working with canvas graphics.</p>
<p style="font-size:12px">While this base64 solution works, I'm not satisfied with it as I believe it would be easier to maintain and read if one could link to an external .woff file in one line instead of the million line bloat required by the base64 encoded string. And, yes I tried that, and no dice.</p>
<p>SVG</p>
<div style="border:1px solid #000000; width:200px;height:100px">
<svg id="svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="100">
<circle cx="0" cy="0" r="80" fill="teal" />
<text x="20" y="25" style="stroke:#333333;font-family:Tahoma,sans-serif;font-size: 32px;">Hello World</text>
</svg>
</div>
<hr />
CSS
body{
font-family: Tahoma, Helvetica;
color:#666;
}
img {
width:200px;
height:100px;
border:1px solid black;
}
JavaScript
var convertSVGtoCanvas = function(){
var svgViz = document.getElementById("svg");
var svgData = new XMLSerializer().serializeToString( svgViz );
var canvasdata = 'data:image/svg+xml;base64,'+ btoa( unescape( encodeURIComponent(svgData) ) );
var imgContainer = document.createElement( "div" );
$(imgContainer).css( "opacity", "1" );
imgContainer.setAttribute( "id", "imgContainer" );
var img = document.createElement( "img" );
img.setAttribute( "width", "200px" );
img.setAttribute( "height", "200px" );
$("body").append( imgContainer );
$("#imgContainer").append("<p>IMG</p>");
$("#imgContainer").append(img);
img.onload = function(){
ctx.drawImage( img,0,0,200,200 );
//$(imgContainer).remove();
}
/*
setTimeout( function(){
ctx.drawImage( img );
alert("hey")
},500);
*/
img.setAttribute( "src", canvasdata );
}
convertSVGtoCanvas();