【发布时间】:2021-08-08 22:58:00
【问题描述】:
我想在画布中填充文本作为 Subscript 和 Superscript 选项。我如何做到这一点。
请帮忙。
【问题讨论】:
-
你想要下标/上标的只是数字吗?
-
我想在上标中添加文本,在下标中添加数字
标签: canvas html5-canvas
我想在画布中填充文本作为 Subscript 和 Superscript 选项。我如何做到这一点。
请帮忙。
【问题讨论】:
标签: canvas html5-canvas
由于不允许在 drawText 中使用 HTML,因此您不能使用 <sup> 和 sub。而是必须自己做。
换句话说,当您想要上标时,您需要将字体更改为更小,或者在更高的 y 位置绘制文本,或者设置textBaseline = "top"。对于下标,你必须做类似的事情。
否则你可以使用 unicode。例如写是有效的:
ctx.fillText('x₂', 50, 50);、ctx.fillText('normalText0123₀₁₂₃₄₅₆₇₈₉', 50, 50);等
【讨论】:
ctx.fillText(String.fromCharCode(178),50,50)之类的东西,代表上标2²
答案和 cmets 是完美的,我想补充一点,您可以通过将字符代码移动 8272 轻松地将数字转换为下标,这对应于“₀”(代码 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);
<canvas id='myCanvas' width='200' height='50'></canvas>
这显然只是一个将所有数字转换为下标的快速示例,不一定是您一直想要的!
更有用的可能是将数值直接转换为下标,您可以遍历所有数字并创建一个字符串,其中包含“₀”(代码 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);
<canvas id='myCanvas' width='200' height='50'></canvas>
【讨论】:
你可以使用函数sub(),例如:
var string = "2";
document.write("x" + string.sub());
document.write(" y" + string.sup());
【讨论】: