javascript - 保持文本动态更新并位于 Canvas 中央

标签 javascript html css canvas

我有以下 Canvas :

<canvas id="myCanvas" width="400" height="400" style="border:0px;">
Your browser does not support the HTML5 canvas tag.</canvas>

JavaScript:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(200, 200, 100, 0, 2 * Math.PI);
ctx.stroke();

我想在 Canvas 中心写下乐谱:

var score = 0;score++;
ctx.fillText(score,200,200);

但是,此分数将会更新,并且此值的位数越多,其中心位置就越不集中。

我尝试使用提供的解决方案 here ,但这里的“文本”只是一个名为 Score 的 JavaScript 变量,因此不被视为文本。

这是我尝试解决我的问题的 fiddle : https://jsfiddle.net/27xfvLhh/

我看到有两种可能的方法来获得想要的结果:

  1. 有没有办法直接填充 Canvas 居中的文本?
  2. 有没有办法计算文本的大小?

谢谢

最佳答案

Is there a way to fill the text directly centered within my canvas?

您可以使用属性 textAlign 进行水平对齐,使用 textBaseline 进行垂直对齐。然后通过例如使用 Canvas 大小的一半来计算中心点:

Is there a way to calculate what will be the size of the text?

ctx.measureText("Text").width 将为您提供使用当前设置字体的文本宽度(以像素为单位)。

var ctx = c.getContext("2d");
ctx.font = "32px sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("Some Centered Text", ctx.canvas.width>>1, ctx.canvas.height>>1);

// measure text
var width = ctx.measureText("Some Centered Text").width;
ctx.font = "20px sans-serif";
ctx.fillText(width + "px", ctx.canvas.width>>1, 90 + ctx.canvas.height>>1);
#c {border:1px solid}
<canvas id=c width=600 height=300></canvas>

关于javascript - 保持文本动态更新并位于 Canvas 中央,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48698214/

相关文章:

html - 在某些情况下使用 css 隐藏文本并避免搜索引擎惩罚?

javascript - Knex 错误 : missing FROM-clause entry for table

javascript - 激活/停用 leaflet.js 上的图层

jquery - 如何在jquery中触发邻居元素到 "this"对象

javascript - 上一个脚本完成后运行 jQuery 代码

html - Magic table 不受 CSS 影响,这是什么魔法?

css - 有没有办法在 Angular2 组件内的 ng-content 中使用 css?

javascript - 将变量从 javascript 文件传递​​到另一个 html 页面

javascript - 文本到数字的转换

css - 如何选择没有类的元素?