Draw SVG on HTML5 Canvas with support for font element
Is there a good library for converting SVG to HTML canvas that supports the font element? I have already tried canvg, but it does not support Font.
Solution 1:
Browsers that support HTML5 Canvas also support SVG pretty well themselves. As such, you could do this:
var img = new Image;
img.onload = function(){ myCanvasContext.drawImage(img,0,0); };
img.src = "foo.svg";
The only downside to this technique is that if the SVG is outside of your domain the canvas will become tainted; you will not be able to use getImageData()
to read the resulting SVG, if that is your goal.
I've put an example of this technique on my server: http://phrogz.net/tmp/canvas_from_svg.html
I've tested this and verified that it works (and looks the same) on IE9, Chrome v11b, Safari v5, and Firefox v4.
[Edit] Note that:
Chrome and Firefox currently 'punt' on security and disallow you from reading the canvas (e.g.these have been fixedgetImageData()
ortoDataURL()
) after you draw any SVG to the canvas (regardless of the domain)Firefox currently has a bug where it refuses to draw SVG to the canvas unless the SVG has
height
andwidth
attributes specified.
Solution 2:
In case you have the svg embedded into HTML or as a raw source you can use a data URL to convert the svg to a HTML image element which you then can draw on the canvas:
var img = new Image();
// here attach an onload handler that draws the image on the canvas
// svgSource is the raw svg xml
img.src = "data:image/svg+xml," + encodeURIComponent(svgSource);
Solution 3:
I just tried a simple img tag, Phrogs' method and canvg. My SVG has an embedded PNG. That only worked in canvg. The others showed the image without the embedded PNG. That was on Android Jellybean with either the standard browser or Chrome.