18

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?

jk.
  • 14,365
  • 4
  • 43
  • 58
RFF
  • 271
  • 1
  • 2
  • 10

2 Answers2

32

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);
bobince
  • 528,062
  • 107
  • 651
  • 834
0

working example

http://jsfiddle.net/sbYPj/

Eval time :)

iterate through num and this will work just fine

var num = value;
var uni = '"\\u' + num+'"';
var result;
if (/^[A-F\d]{4}$/.test(num)) 
{
  result = eval(uni);
}
samccone
  • 10,746
  • 7
  • 43
  • 50
  • 1
    Undone the downvote since the regex check removes the immediate vulnerability, but still `eval` is slow, ugly, dangerous and [usually](http://stackoverflow.com/questions/86513/why-is-using-javascript-eval-function-a-bad-idea) best avoided. – bobince Aug 17 '11 at 19:06
  • 1
    [This is what I first thought when I read the answer.](http://www.youtube.com/watch?v=TO5wryDdEI0) I've used all my upvotes for the day; I'll try to remember to come back in four hours. – sdleihssirhc Aug 17 '11 at 19:16