Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem understanding canvas fillText with unicode characters

I want to display the special characters in a font using canvas fillText. The code is basically:

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?

like image 277
RFF Avatar asked Aug 17 '11 18:08

RFF


1 Answers

Use String.fromCharCode to turn a number into a character.

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 apply to pass them as arguments to fromCharCode. This is faster than doing string= string+String.fromCharCode(c) for each character separately.

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);
like image 150
bobince Avatar answered Sep 18 '22 14:09

bobince