在矩形顶部绘制文本

fes*_*fes 4 html5 drawing canvas

我正试图在矩形的角落画一些文字,但我刚开始在一个矩形上绘制文字,然后才解决定位问题.我似乎无法绘制一个矩形,用一种颜色填充它然后在它上面绘制文字.即使我先绘制文本,然后是矩形,然后填写这些顺序,矩形似乎与文本重叠.

此代码将显示没有填充的文本和矩形

context.beginPath();

for (var i = 0; i < 8; i++) {
    context.font = "18pt Arial";
    context.fillText("blah", 0, 0 + (i * 50));
    context.rect(30, 0 + (i * 50), 50, 50);
}

context.lineWidth = 0.1;
context.strokeStyle = "black";
context.stroke();
Run Code Online (Sandbox Code Playgroud)

此代码将显示文本并填充矩形,但文本似乎显示在矩形下方.

context.beginPath();

for (var i = 0; i < 8; i++) {
   context.font = "18pt Arial";
   context.fillText("blah", 0, 0 + (i * 50));
   context.rect(30, 0 + (i * 50), 50, 50);
}

context.fillStyle = "#33cc00";
context.fill();
context.lineWidth = 0.1;
context.strokeStyle = "black";
context.stroke();
Run Code Online (Sandbox Code Playgroud)

我有什么想法我做错了吗?

Phr*_*ogz 9

HTML5 Canvas上的每个绘制操作都在顶部绘制,并且(通常)会消除下面的任何内容.如果要在矩形顶部绘制文本,则必须fillText() 调用fill()已创建的rects 调用.

什么订单绘图命令添加到路径无关紧要,当fill()发生时确定何时应用瞬间干燥的墨水.由于您在所有fillText()呼叫之后执行此操作,因此矩形将绘制在顶部.

我会像这样修改你的代码:

context.font = "18pt Arial";
context.strokeStyle = "#000";
context.lineWidth = 0.1;
for (var i=0; i<8; i++) {
   context.fillStyle = "#3c0";
   context.fillRect(30, 0 + (i * 50), 50, 50);
   context.strokeRect(30, 0 + (i * 50), 50, 50);
   context.fillStyle = "#fff";
   context.fillText("blah", 0, 0 + (i * 50));
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您不想使用fillRect()/strokeRect():

context.font = "18pt Arial";
context.strokeStyle = "#000";
context.lineWidth = 0.1;
for (var i=0; i<8; i++) {
   context.beginPath();
   context.fillStyle = "#3c0";
   context.rect(30, 0 + (i * 50), 50, 50);
   context.fill();
   context.stroke();

   context.fillStyle = "#fff";
   context.fillText("blah", 0, 0 + (i * 50));
}
Run Code Online (Sandbox Code Playgroud)