简体   繁体   English

Unicode字符在HTML5画布中无法正确呈现

[英]Unicode characters not rendering properly in HTML5 canvas

I am trying to render a unicode treble clef using the HTML5 canvas element. 我正在尝试使用HTML5 canvas元素渲染一个unicode高音谱号。 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 当使用正确的字符代码(特别是1D120)时,它在HTML中渲染得很好,但是当我尝试在画布中使用它时会出现一个奇怪的角色

The following code is in my javascript file which works its magic on the canvas... 以下代码在我的javascript文件中,它在画布上发挥作用......

 var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); context.font = "48px serif"; context.strokeText("\ᴒ0", 10, 50); 
 <h1>&#x1D120;</h1> <canvas id="canvas" width="100" height="100"> </canvas> 

Unfortunately I can't put a picture of the character because my rep is too low as of yet. 不幸的是,我不能把这个角色的照片,因为我的代表太低了。

Any insight into what might be causing this problem is appreciated. 任何洞察可能导致此问题的原因都表示赞赏。 Thanks in advance! 提前致谢!

JavaScript strings use UTF-16 encoding. JavaScript字符串使用UTF-16编码。 Your character requires a two-part escape because it's a 3-byte UTF-8 sequence codepoint that requires 2 UTF-16 characters. 你的角色需要两部分逃脱,因为它是一个 3字节的UTF-8序列 码点,需要2个UTF-16字符。

Stolen from a blog post by somebody smarter than me is this handy function: 比我更聪明的人博客文章中偷来是这个方便的功能:

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

When you invoke that with your code: 当您使用代码调用它时:

var treble = toUTF16(0x1D120);

you get back "\?\?" . 你回来了"\?\?"

Thanks again to Dr. Axel Rauschmayer for the code above — read the excellent linked blog post for more information. 再次感谢Axel Rauschmayer博士的上述代码 - 阅读优秀的链接博客文章了解更多信息。

将十六进制值括在{}内,如下所示:

context.strokeText("\u{1D120}", 10, 50);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM