Reputation: 2625
I have this example in canvas. I would like to know how I can add text in shapes.
I have looked into the code that draws shapes but not really sure how to add text. I was able to add text but it doesn't move with balls?
function draw()
{
context.clearRect(0, 0, stageWidth, stageHeight);
var i = balls.length;
while(--i > -1)
{
context.fillStyle = balls[i].color;
context.beginPath();
context.arc(balls[i].x,balls[i].y,balls[i].size,0,Math.PI*2,true);
context.closePath();
context.fill();
}
}
Upvotes: 0
Views: 1631
Reputation: 9813
You just have to use the ball's x and y value to make sure the text follow the ball, and use textAlign
and textBaseline
to easily align the text.
function draw()
{
context.clearRect(0, 0, stageWidth, stageHeight);
// Align once an for all.
context.textAlign = 'center'; // Set text align to center.
context.textBaseline = 'middle'; // Set text vertical align to middle.
var i = balls.length;
while(--i > -1)
{
context.fillStyle = balls[i].color;
context.beginPath();
context.arc(balls[i].x,balls[i].y,balls[i].size,0,Math.PI*2,true);
context.closePath();
context.fill();
// Easier to see the text.
context.fillStyle = 'black';
// Draw text `Ball # i` centered at position (x, y),
// with the width of the text equal to ball's size * 2.
context.fillText('Ball #' + i, balls[i].x ,balls[i].y, balls[i].size * 2);
}
}
See altered jsfiddle, is that what you want?
P.S : When playing with canvas, it's always best to keep HTML5 Canvas Cheat Sheet handy.
Upvotes: 2