canvas中文显示乱码 html5_Unicode字符无法在HTML5画布中正确呈现

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

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

𝄠

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

}

When you invoke that with your code:

var treble = toUTF16(0x1D120);

you get back "\uD834\uDD20".

Thanks again to Dr. Axel Rauschmayer for the code above — read the excellent linked blog post for more information.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值