CanvasRenderingContext2D.prototype.roundRect = function (
x,
y,
width,
height,
radius
) {
if (width < 2 * radius) radius = width / 2;
if (height < 2 * radius) radius = height / 2;
this.beginPath();
this.moveTo(x + radius, y);
this.arcTo(x + width, y, x + width, y + height, radius);
this.arcTo(x + width, y + height, x, y + height, radius);
this.arcTo(x, y + height, x, y, radius);
this.arcTo(x, y, x + width, y, radius);
this.closePath();
return this;
};
let generateCanvas = function (config) {
var tmpCanvas = document.createElement("canvas");
var tmpContext = tmpCanvas.getContext("2d");
tmpContext.font = tmpContext.font.replace(/\d+px/, config.fontSize);
var textWidth = tmpContext.measureText(config.text).width || 10;
tmpCanvas = null;
var textCanvas = document.createElement("canvas");
var textContext = textCanvas.getContext("2d");
textCanvas.height = config.height;
textCanvas.width = textWidth;
textCanvas.width = textWidth + 2 * config.padding;
textContext.lineWidth = config.lineWidth;
textContext.strokeStyle = config.lineColor;
textContext.fillStyle = config.backgroundColor;
textContext.roundRect(
0,
0,
textCanvas.width,
textCanvas.height,
config.rounded
);
textContext.stroke();
textContext.fill();
textContext.fillStyle = config.color;
textContext.font = textContext.font.replace(/\d+px/, config.fontSize);
textContext.textAlign = config.textAlign;
textContext.textBaseline = config.textBaseline;
textContext.fillText(
config.text,
textCanvas.width / 2,
config.height / 2
);
return textCanvas;
};
The config I passed to the generateCanvas function is:
{
text: "测试名称测试名称测试名称测试名称",
height: 40,
fontSize: "24px",
textAlign: "center",
textBaseline: "middle",
color: "#F9A403",
backgroundColor: "white",
lineColor: "transparent",
rounded: 25,
padding: 10,
}
Why is the text in the image generated by the above function not centered vertically? roundRect is a custom function that implements drawing a rectangle with rounded corners using canvas.Please help me if there are any gods to look at this problem.
