【发布时间】:2016-06-06 20:35:18
【问题描述】:
我正在尝试使用简单的脚本将文本绘制到标志上。除了没有加载字体外,它工作正常。
我尝试在本地和网络上加载字体,但两者都不能在我的服务器上工作。
但是代码在w3 schools tryit editor上运行良好
我认为这与字体加载不正确或太迟有关。确保正确加载字体的最佳方法是什么?
<!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>
【问题讨论】:
-
是什么让您认为当您的画布 JS 代码启动时字体已经可用?我没有看到任何检查以确保字体甚至完成下载/解析/附加到图形上下文的代码...?
标签: javascript canvas fonts