Unicode字符无法在HTML5画布中正确呈现 [英] Unicode characters not rendering properly in HTML5 canvas
问题描述
我想使用HTML5 canvas元素来呈现unicode高音谱号。当使用正确的字符代码(特别是1D120)时,它在HTML中呈现得很好,但是当我尝试在canvas中使用它时,会出现一个奇怪的字符
I am trying to render a unicode treble clef using the HTML5 canvas element. When using the correct character code (specifically 1D120), it renders fine in HTML, but when I try to use it inside of a canvas a weird character appears
在我的javascript文件中,它在画布上工作的神奇...
The following code is in my javascript file which works its magic on the canvas...
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.font = "48px serif";
context.strokeText("\u1D120", 10, 50);
<h1>𝄠</h1>
<canvas id="canvas" width="100" height="100">
</canvas>
因为我的代表太低了。
任何洞察到什么可能导致这个问题是值得赞赏的。提前感谢!
Any insight into what might be causing this problem is appreciated. Thanks in advance!
推荐答案
JavaScript字符串使用UTF-16编码。您的字符需要两部分转义,因为它是一个 3字节的UTF-8序列代码点,需要2个UTF-16字符。
JavaScript strings use UTF-16 encoding. Your character requires a two-part escape because it's a 3-byte UTF-8 sequence codepoint that requires 2 UTF-16 characters.
从某人比我聪明的博客这个方便的功能:
function toUTF16(codePoint) {
var TEN_BITS = parseInt('1111111111', 2);
function u(codeUnit) {
return '\\u'+codeUnit.toString(16).toUpperCase();
}
if (codePoint <= 0xFFFF) {
return u(codePoint);
}
codePoint -= 0x10000;
// Shift right to get to most significant 10 bits
var leadSurrogate = 0xD800 + (codePoint >> 10);
// Mask to get least significant 10 bits
var tailSurrogate = 0xDC00 + (codePoint & TEN_BITS);
return u(leadSurrogate) + u(tailSurrogate);
}
当您使用代码调用时:
var treble = toUTF16(0x1D120);
您会回到\\\�\\\�
。
再次感谢Axel Rauschmayer博士上面的代码—阅读优秀的链接博客文章了解更多信息。
Thanks again to Dr. Axel Rauschmayer for the code above — read the excellent linked blog post for more information.
这篇关于Unicode字符无法在HTML5画布中正确呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!