简体   繁体   中英

Canvas fill shape with text

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();
                }
            }

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?

PS : When playing with canvas, it's always best to keep HTML5 Canvas Cheat Sheet handy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM