【问题标题】:How to align text by decimal point in HTML5 Canvas如何在HTML5 Canvas中对十进制点对齐文本
【发布时间】:2018-08-20 22:16:52
【问题描述】:

假设我有三个数字

2.55

2353.45

232.44

我想在画布上写三个数字按照小数点对齐,如下所示。

     2.55

  2353.45

   232.44

我知道 context.textAlign 属性,但它只有 5 个选项:left、right、center、start、end。 我在互联网上搜索过,但找不到任何帮助。请帮助。

【问题讨论】:

  • stackoverflow.com/help/how-to-ask 请包含一个代码 sn-p ,其中显示您拥有哪些不起作用,并说明预期结果是什么。帮助我们重现问题。
  • textAlign right 应按小数点对齐(假设所有小数位数相同)
  • 看看编辑

标签: javascript jquery html html5-canvas


【解决方案1】:

您可以使用measureText() 方法及其返回的TextMetrics 对象来计算点之前数字的宽度。

var canvas = document.getElementById('canvas'),
  ctx = canvas.getContext('2d'),
  texts = [];
ctx.font = '14px sans-serif';
// fill our array with test-cases
for(var i=0; i<7; i++)
  texts.push(randLengthedNum() + '.' + randLengthedNum());

texts.forEach(drawText);

function drawText(str, i) {
  var left_part = str.split('.')[0],
    // get the width of the left part
    left_width = ctx.measureText(left_part).width,
    // the width of the dot
    dot_width = ctx.measureText('.').width,
    // places the '.' at center of the canvas
    x = (canvas.width / 2) - (left_width + (dot_width / 2));
  ctx.fillText(str, x, (i+1) * 20);
}

// return random lengthed numbers
function randLengthedNum(){
  return (Math.random()).toFixed(2+(Math.random()*8)|0).substr(2);
}
#canvas{
  border: 1px solid;
}
&lt;canvas id="canvas"&gt;&lt;/canvas&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多