I'm trying to draw text onto a flag using a simple script. It works fine except for the Font not being loaded.
I've tried to load the font locally and from the web, but both don't work on my server.
However the code runs fine on w3 schools tryit editor
I think it has to do with the font not being loaded correctly or too late. What is the best way to make sure the font is loaded correctly?
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Ubuntu:regular,bold&subset=Latin">
<style>body { font-family: Ubuntu, sans-serif; }</style>
</head>
<body>
<canvas style="border-radius: 100px;" id="myCanvas" width="200" height="200">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var size = 200
var textSize=size * 0.55;
var countryCode = "nl";
var text = "123";
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image;
img.onload = function(){
ctx.drawImage(img,-1,-1,size,size); // removes the 1px border the flags sometimes have
ctx.font = textSize+"px Ubuntu";
ctx.textAlign="center";
ctx.fillStyle = "#260C4D";
ctx.fillText(text,size/2,size/2 + textSize / 2.85);
};
img.src = "http://www.geonames.org/flags/x/"+countryCode+".gif";
</script>
</body>
</html>