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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With