(HTML5) cannot display Chinese characters when usi

2019-06-02 10:23发布

问题:

I am trying to display some Chinese characters on my web page using HTML5.

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

// ...

context.fillText('中文', 0, 0);

context.fill();

And I have checked several questions here and added the following in the header.

<meta charset="UTF-8" />

I tried in Firefox 14, and it shows ???? on the screen. While I realized that, my browser setting of character encoding is UTF-8. When I changed it to 'Big5`, it displays well.

My question is, can the script allow browser to display Chinese (and perhaps all other non-English) characters properly without changing to the specific character encoding? i.e. keeping the setting as UTF-8 and then nothing deal with the user's browsers furthermore because I want my page to display more than one language.

Thanks.

回答1:

You seem to have saved your source code in Big5. You should either

  • save your source code as UTF-8, OR
  • use unicode escape codes for non-ASCII characters.

If you prefer to use escape codes, your example can be written as:

context.fillText('\u4e2d\u6587', 0, 0);