Reputation: 2717
i am trying to figure out how to add a text to a canvas shape for example here is my Code:
var text ="5"; // text to display over the circle
context.fillStyle = "red";
context.beginPath();
context.arc(50,70, 10, 0, Math.PI * 2);
context.closePath();
context.fill();
i would very much appriciate it if someone would help me adding the text to the shape thanks in advance.
EDIT i figure out that i need to write again on the canvas so this is what i got so far ... but the text doesnt allign to the center of the circle :
context.fillStyle = "red";
context.beginPath();
var radius = 10; // for example
context.arc(200, 200, radius, 0, Math.PI * 2);
context.closePath();
context.fill();
context.fillStyle = "black"; // font color to write the text with
var font = "bold " + radius +"px serif";
context.font = font;
context.textBaseline = "top";
context.fillText(text, 200-radius/4 ,200-radius/2);
Upvotes: 3
Views: 20390
Reputation: 63820
As you can see here:
The text is getting drawn starting in the center of the circle, and starting with the top of the text since you put the textBaseline
to top
.
This is the same text centered roughly using the width and height of the text:
As you can see we have a context.measureText(theTextToMeasure)
function that returns a textMetrics
object that has a width property. For now it does not have a height one, so we have to sort of guess that.
Upvotes: 9