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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:57:49  来源:igfitidea点击:

Problem understanding canvas fillText with unicode characters

javascripthtmlhtml5-canvas

提问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.fromCharCodeto 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 applyto 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

工作示例

http://jsfiddle.net/sbYPj/

http://jsfiddle.net/sbYPj/

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);
}