HTML5 Canvas +下标和上标

bal*_*dai 10 canvas html5-canvas

我想在画布中填充文本作为Subsccript和Superscript选项.我怎么做到这一点.

请帮忙.

Sim*_*ris 12

由于您不允许使用HTML,drawText因此无法使用<sup>sub.而是必须自己做.

换句话说,当您需要上标时,您需要将字体更改为更小,并将文本绘制在更高的y位置或设置textBaseline = "top".对于下标,你必须做类似的事情.

否则你可以使用unicode.例如,它有效写:

ctx.fillText('x?', 50, 50);,ctx.fillText('normalText0123??????????', 50, 50);等等.

  • 在unicode上扩展,可以编写类似`ctx.fillText(String.fromCharCode(178),50,50)`的东西,它代表上标2和#178; (4认同)
  • 为完整起见:下标:₀ ₁ ₂ ₃ ₄ ₅ ₆ ₇ ₈ ₉ 和上标:⁰ ¹ ² ³ ⁴ ⁵ ⁶ ⁷ ⁸ ⁹ (3认同)

Max*_*eel 5

答案和评论是完美的,我想补充一点,您可以通过将字符代码移动8272轻松地将数字转换为下标数字,这对应于"0"(代码8320)的字符代码与"0"的字符代码之间的差异. "(代码48).

例如:

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);
Run Code Online (Sandbox Code Playgroud)
<canvas id='myCanvas' width='200' height='50'></canvas>
Run Code Online (Sandbox Code Playgroud)

这显然只是一个快速的例子,将所有数字转换为下标,不一定是你一直想要的!

更有用的可能是直接将数值转换为下标,您可以遍历所有数字并创建一个字符串,其字符在"0"(代码8320)和"₉"(代码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);
Run Code Online (Sandbox Code Playgroud)
<canvas id='myCanvas' width='200' height='50'></canvas>
Run Code Online (Sandbox Code Playgroud)