HTML5 Canvas + Subscript and Superscript

后端 未结 2 911
旧巷少年郎
旧巷少年郎 2021-01-04 13:29

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

Please help.

2条回答
  •  独厮守ぢ
    2021-01-04 14:04

    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= 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);

    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);

提交回复
热议问题