html - 在矩形顶部绘制文本

标签 html canvas drawing

我正在尝试在矩形的角上绘制一些文本,但在处理定位之前我刚开始在矩形上绘制文本。我似乎无法绘制一个矩形,用一种颜色填充它,然后在其上绘制文本。即使我先绘制文本,然后绘制矩形,然后填写这些顺序,矩形似乎只是与文本重叠。

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

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

此代码将向我显示文本并填充在矩形中,但文本似乎出现在矩形下方。

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

知道我做错了什么吗?

最佳答案

HTML5 Canvas 上的每个绘制操作都会在上面绘制并(通常)抹掉下面的任何内容。如果您希望文本绘制在矩形之上,您必须在为您拥有的矩形调用 fill() 之后调用 fillText() 已创建。

添加到路径中的绘图命令的顺序无关紧要,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));
}

或者,如果您不想使用 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));
}

关于html - 在矩形顶部绘制文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5573594/

相关文章:

javascript 在 Canvas 上绘制图像

canvas - 是否可以在 reportlab 文档中使用工具提示或悬停效果?

c# - 从 base64string 生成缩略图 C#

c# - 不同的内置图像抽象的优点是什么?

C# 随机颜色生成器无法正常工作

javascript - 如何动态添加表格行

html - Foundation ZURB 自定义表单选择选项错误

javascript - 禁用按钮 30 秒

html - 如何在 iPhone/iOS 上删除电话号码的蓝色样式?

JAVA - swing - 使用目标 Canvas 的反转/否定颜色进行绘制/填充