canvas怎么让圆角矩形里面的文字居中
时间: 2023-11-10 08:54:34 浏览: 38
在 canvas 中,可以使用 `textAlign` 属性和 `textBaseline` 属性来实现文字的居中对齐。具体方法如下:
1. 设置矩形圆角
```js
ctx.roundRect(x, y, width, height, radius);
```
其中,`roundRect` 是自定义的绘制圆角矩形的方法,`x`、`y`、`width`、`height` 分别表示矩形的左上角坐标和宽高,`radius` 表示圆角的半径。
2. 设置文字样式
```js
ctx.font = "16px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
```
其中,`font` 表示文字的大小和字体,`textAlign` 表示文字的水平对齐方式,可以设置为 `"left"`、`"center"` 或 `"right"`,`textBaseline` 表示文字的垂直对齐方式,可以设置为 `"top"`、`"middle"` 或 `"bottom"`。
3. 绘制文字
```js
ctx.fillText(text, x + width / 2, y + height / 2);
```
其中,`text` 表示要绘制的文字,`x + width / 2` 和 `y + height / 2` 分别表示矩形的中心坐标。
完整的代码示例:
```js
// 绘制圆角矩形
CanvasRenderingContext2D.prototype.roundRect = function (x, y, width, height, radius) {
if (typeof radius === "undefined") {
radius = 5;
}
this.beginPath();
this.moveTo(x + radius, y);
this.lineTo(x + width - radius, y);
this.quadraticCurveTo(x + width, y, x + width, y + radius);
this.lineTo(x + width, y + height - radius);
this.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
this.lineTo(x + radius, y + height);
this.quadraticCurveTo(x, y + height, x, y + height - radius);
this.lineTo(x, y + radius);
this.quadraticCurveTo(x, y, x + radius, y);
this.closePath();
return this;
};
// 绘制圆角矩形内居中的文字
function drawTextInRoundRect(ctx, text, x, y, width, height, radius) {
// 设置圆角矩形的样式
ctx.roundRect(x, y, width, height, radius);
ctx.fillStyle = "#fff";
ctx.fill();
// 设置文字的样式
ctx.font = "16px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
// 绘制文字
ctx.fillStyle = "#000";
ctx.fillText(text, x + width / 2, y + height / 2);
}
// 使用示例
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
drawTextInRoundRect(ctx, "Hello World!", 50, 50, 100, 50, 10);
```