Pregunta

Me gustaría llenar el texto en el lienzo como opciones de subsccript y superscript. ¿Cómo hago esto?

Por favor ayuda.

¿Fue útil?

Solución

Ya que no se le permite usar HTML en drawText no puedes usar <sup> y sub. En cambio, tengo que hacerlo tú mismo.

En otras palabras, cuando desee SuperScript, deberá cambiar la fuente para que sea más pequeña y dibujar el texto en una posición Y más alta o de lo contrario textBaseline = "top". Para el subíndice tendrá que hacer similar.

De lo contrario, puede usar Unicode. Por ejemplo, es válido para escribir:

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

Otros consejos

La respuesta y los comentarios son perfectos, quería agregar que puede convertir fácilmente los números a los subíndices cambiando el código de caracteres por 8272, que corresponde a la diferencia entre el código de carbón para "₀" (código 8320) y eso para "0 "(Código 48).

Por ejemplo:

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>

Obviamente, es solo un ejemplo rápido que convierte todos los números en subíndice, ¡no necesariamente lo que siempre desearía!

Algo más útil puede ser convertir un valor numérico en un subíndice directamente, puede recorrer todos los dígitos y crear una cadena con caracteres entre "₀" (código 8320) y "₉" (código 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>

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top