我正在尝试在用HTML Canvas绘制的圆的中间插入文本,但该文本总是出现在中心上方。 (我尝试了基准,但是没有用)。我不想对fillText坐标进行硬编码。

var canvas = document.getElementById('completionStatus');

var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 200;

context.beginPath();
context.fillStyle = '#B8D9FE';
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fill();
context.strokeStyle = '#ffffff';
context.font = 'bold 130pt Calibri';
context.textAlign = 'center';
context.fillStyle = 'white';
context.fillText('70%', centerX, centerY);
context.stroke();
<canvas id="completionStatus" width="400" height="400"></canvas>


这是一个小提琴:http://jsfiddle.net/wku0j922/2/

最佳答案

只需在上下文中使用textBaseline属性。将textBaselinemiddle都设置为textAlign时,您可以将其精确放置在圆心的位置,并且将其整个面板居中。

var c1 = document.getElementById('c1');
var c2 = document.getElementById('c2');
var ct1 = c1.getContext('2d');
var ct2 = c2.getContext('2d');

c1.width = c2.width = 200;
c1.height = c2.height = 200;

ct1.font = ct2.font = '20px Helvetica';

ct1.textAlign = ct2.textAlign = 'center';
ct2.textBaseline = 'middle';

ct1.beginPath();
ct1.arc(100,100,99,0,Math.PI * 2);
ct1.stroke();
ct1.closePath();

ct2.beginPath();
ct2.arc(100,100,99,0,Math.PI * 2);
ct2.stroke();
ct2.closePath();

ct1.fillText('textBaseline not set', 100, 100);
ct2.fillText('textBaseline middle', 100, 100);
<canvas id="c1"></canvas>
<canvas id="c2"></canvas>


这是在您的代码段中实现的:

var canvas = document.getElementById('completionStatus');

var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 200;

context.beginPath();
context.fillStyle = '#B8D9FE';
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fill();
context.strokeStyle = '#ffffff';
context.font = 'bold 130pt Calibri';
context.textAlign = 'center';
context.textBaseline = 'middle';
context.fillStyle = 'white';
context.fillText('70%', centerX, centerY);
context.stroke();
<canvas id="completionStatus" width="400" height="400"></canvas>


文件:https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/textBaseline

09-17 09:38