Frage

Ich möchte Text in Canvas als SubScript- und Superscript -Optionen füllen. Wie mache ich das?

Bitte helfen Sie.

War es hilfreich?

Lösung

Da dürfen Sie HTML nicht verwenden drawText Sie können nicht verwenden <sup> und sub. Muss es stattdessen selbst tun.

Mit anderen Worten, wenn Sie Superscript möchten textBaseline = "top". Für ein Index müssen Sie ähnlich tun.

Andernfalls können Sie Unicode verwenden. Zum Beispiel ist es gültig zu schreiben:

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

Andere Tipps

Die Antwort und die Kommentare sind perfekt. Ich wollte hinzufügen, dass Sie Nummern leicht in die Einzeichnungen umgeben können, indem Sie den Zeichencode um 8272 verschieben, was der Differenz zwischen dem Zeichencode für "₀" (Code 8320) und der für "0 entspricht "(Code 48).

Zum Beispiel:

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>

Es ist offensichtlich nur ein kurzes Beispiel, das alle Zahlen in ein Einweis umwandelt, nicht unbedingt das, was Sie immer wollen würden!

Etwas Nützlicheres kann darin bestehen, einen numerischen Wert direkt in ein Index umzuwandeln. Sie können alle Ziffern durchlaufen und eine Zeichenfolge mit Zeichen zwischen "₀" (Code 8320) und "₉" (Code 8329) erstellen:

//  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>

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top