Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw text on top of rectangle

I'm trying to draw some text in the corner of a rectangle but I just started off drawing text on a rectangle before tackling the positioning. I can't seem to draw a rectangle, fill it with a color and then draw text over it. Even if i draw the text first, then rectangle, then fill in those orders, the rectangle just seems to overlap the text.

This code will show text and rectangles with no fill

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

This code will show me the text and filled in rectangles but the text seems to appear below the rectangles.

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

Any ideas what I'm doing wrong?

like image 944
fes Avatar asked Apr 06 '11 22:04

fes


1 Answers

Every paint operation on an HTML5 Canvas draws on top of and (in general) obliterates whatever was underneath. If you want text to draw on top of the rectangles, you must call fillText() after you call fill() for the rects you have created.

It doesn't matter what order drawing commands are added to the path, it is when the fill() occurs that determines when the instantly-drying ink is applied. Since you do this after all your fillText() calls, the rectangles are drawn on top.

I would modify your code like this:

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

Alternatively, if you don't want to use 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));
}
like image 157
Phrogz Avatar answered Sep 21 '22 00:09

Phrogz