在圆圈下面绘制文字

时间:2015-05-17 02:34:20

标签: javascript html html5 canvas

我使用html5 canvas和js。

绘制一个圆圈
var canvas = document.getElementById(key);
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 35;

context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'red';
context.fill();
context.stroke();

我还想在它下面画一个文字。我试过这个:

    context.closePath();
    context.fill();
    context.fillStyle = "black";
    context.font = "bold 11";
    context.textBaseline = "top";
    context.fillText('Hello', 100-radius/4 ,100-radius/2); 

但由于某种原因它被绘制在右侧 - 底角,而我想要完全在圆圈下面。

2 个答案:

答案 0 :(得分:2)

textAlign设置为居中,然后半径添加到y位置:

var spacing = 5;
context.textAlign = "center";
context.textBaseline = "top";
context.fillText('Hello', centerX, centerY + radius + spacing); 

答案 1 :(得分:0)

您的文字对齐方式和文字坐标都是错误的。

var margin = 10; // Increase the margin add space between Circle & text
context.textBaseline = "top";
context.textAlign = "center";
context.fillText('Hello', centerX , centerY + radius + margin); 

JSFiddle with desired outcome