Question

I would like to fill text in canvas as Subsccript and Superscript options. How do I acheive this.

Please help.

Was it helpful?

Solution

Since you aren't allowed to use HTML in drawText you can't use <sup> and sub. Instead have to do it yourself.

In other words, when you want superscript you will need to change the font to be smaller and either draw the text at a higher y-position or else set textBaseline = "top". For subscript you will have to do similar.

Otherwise you can use unicode. For instance it is valid to write:

ctx.fillText('x₂', 50, 50);, ctx.fillText('normalText0123₀₁₂₃₄₅₆₇₈₉', 50, 50);, etc.

OTHER TIPS

The answer and comments are perfect, I wanted to add that you can easily convert numbers to subscript ones by shifting the character code by 8272, which corresponds to the difference between the char code for "₀" (code 8320) and that for "0" (code 48).

For example:

var text = "N1234567890";

function subNums(str)
{
    var newStr = "";
  
    for (var i=0; i<str.length; i++)
    {
        //  Get the code of the current character
        var code = str.charCodeAt(i);
        if (code >= 48 && code <= 57)
        {
            //  If it's between "0" and "9", offset the code ...
            newStr += String.fromCharCode(code + 8272);
        }
        else
        {
            //   ... otherwise keep the character
            newStr += str[i];
        }
    }
  
    return newStr
}

//  Get the context
var ctx = document.getElementById('myCanvas').getContext('2d');

//  Write the string
ctx.font = "20px serif";
ctx.fillText(text, 0, 20);
ctx.fillText(subNums(text), 0, 40);
<canvas id='myCanvas' width='200' height='50'></canvas>

It's obviously just a quick example that converts all numbers to subscript, not necessarily what you'd always want!

Something more useful may be to convert a numerical value to a subscript directly, you can loop through all digits and create a string with characters between "₀" (code 8320) and "₉" (code 8329):

//  Numerical value to use as subscript
//  Don't start it with 0 otherwise it will be read as an octal value!
var index = 1234567890;

function toSub(value)
{
  var str = "";
  //  Get the number of digits, with a minimum at 0 in case the value itself is 0
  var mag = Math.max(0, Math.floor(Math.log10(value)));
  //  Loop through all digits
  while (mag >= 0)
  {
    //  Current digit's value
    var digit = Math.floor(value/Math.pow(10, mag))%10;
    //  Append as subscript character
    str += String.fromCharCode(8320 + digit);
    mag--;
  }
  return str;
}

//  Get the context
var ctx = document.getElementById('myCanvas').getContext('2d');

//  Write the string
ctx.font = "20px serif";
ctx.fillText("N" + index, 0, 20);
ctx.fillText("N" + toSub(index), 0, 40);
<canvas id='myCanvas' width='200' height='50'></canvas>

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top