As per Mozilla's documentation, you can draw complex HTML on Canvas like this.
What I can't figure out is a way to make Google fonts work with it.
See this example below:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +
'<foreignObject width="100%" height="100%">' +
'<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px;font-family:Pangolin">' +
'test' +
'</div>' +
'</foreignObject>' +
'</svg>';
var DOMURL = window.URL || window.webkitURL || window;
var img = new Image();
var svg = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
var url = DOMURL.createObjectURL(svg);
img.onload = function () {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
}
img.src = url;
<link href="https://fonts.googleapis.com/css?family=Pangolin" rel="stylesheet">
<div style="font-size:40px;font-family:Pangolin">test</div><hr>
<canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas>
This has been already asked a few times, but never really as precise as it about Google Fonts.
So the general ideas are that :
<img>
element first.<img>
inner documents can not make any external requests.This means that you'll have to embed all your external resources as dataURIs inside your svg markup itself, before loading it to the
<img>
element.So for a font, you'll need to append a
<style>
element, and replace font's src in betweenurl(...)
, with the dataURI version.Google fonts embed documents like the one you use are actually just css files which will then point to the actual font files. So we need to fetch not only the first level CSS doc, but also the actual font files.
Here is a annotated and working (?) proof of concept, written with ES6 syntax, so which will require a modern browser, but it could be transpiled quite easily since all the methods in it can be polyfiled.
The first thing you can try is to use Google web font loader because you are generating the svg before the font is loaded by the browser
so you need to make sure that the fonts are loaded and then generate the svg/image
if that doesn't work you can create text tags in your svg and try these alternatives for fonts https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/SVG_fonts