javascript 使用 unicode 字符理解画布填充文本的问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7097584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Problem understanding canvas fillText with unicode characters
提问by RFF
I want to display the special characters in a font using canvas fillText
. The code is basically:
我想使用 canvas 以字体显示特殊字符fillText
。代码基本上是:
canvas = document.getElementById("mycanvas");
context = canvas.getContext("2d");
hexstring = "\u00A9";
//hexstring = "\u" +"00A9";
context.fillText(hexstring,100,100);
If I use the first hexstring
, it works and I get the copyright symbol. If I use the second one, it just displays \u00A9
. Since I need to iterate through the numbers, I need to use the second one to display all the special characters of a font. I am using utf-8. What am I doing wrong?
如果我使用第一个hexstring
,它会起作用并且我得到版权符号。如果我使用第二个,它只会显示\u00A9
. 由于我需要遍历数字,因此我需要使用第二个数字来显示字体的所有特殊字符。我正在使用 utf-8。我究竟做错了什么?
回答by bobince
Use String.fromCharCode
to turn a number into a character.
使用String.fromCharCode
把一个数字的字符。
var c= 169; // 0xA9
context.fillText(String.fromCharCode(c), 100, 100);
If you have a hex-encoded string you can parse that as a hex number first:
如果您有一个十六进制编码的字符串,您可以先将其解析为十六进制数:
var h= '00A9';
String.fromCharCode(parseInt(h, 16));
To create a string containing a range of characters, you could create an Array of the numbers and then use apply
to pass them as arguments to fromCharCode
. This is faster than doing string= string+String.fromCharCode(c)
for each character separately.
要创建包含一系列字符的字符串,您可以创建一个数字数组,然后使用apply
它们将它们作为参数传递给fromCharCode
. 这比string= string+String.fromCharCode(c)
分别为每个字符执行要快。
function makeRange(n0, n1) {
var a= [];
for (; n0<n1; n++)
a.push(n0);
}
var someChars= makeRange(0xA9, 0xFF);
var stringOfChars= String.fromCharCode.apply(String, someChars);
回答by samccone
working example
工作示例
Eval time :)
评估时间:)
iterate through num and this will work just fine
迭代 num ,这将工作得很好
var num = value;
var uni = '"\u' + num+'"';
var result;
if (/^[A-F\d]{4}$/.test(num))
{
result = eval(uni);
}