简体   繁体   English

画布用文本填充形状

[英]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. 您只需要使用球的x和y值来确保文本跟随球,并使用textAligntextBaseline即可轻松对齐文本。

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? 请参阅更改的jsfiddle ,这就是您想要的吗?

PS : When playing with canvas, it's always best to keep HTML5 Canvas Cheat Sheet handy. PS:使用画布时,最好始终随手携带HTML5 Canvas Cheat Sheet

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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