2015-05-17 32 views
0

我在用html5畫布和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

設置textAlign到中心,然後添加半徑y位置:

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

我如何加入圈子和文本之間的空間? –

+0

@AlexanderSupertramp只需將空間值添加到混音中心Y +半徑+空格 – K3N

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