Write in Rectangle - HTML Canvas

4

I'm using the following code

var canvas = document.createElement("canvas");
canvas.width = 55;
canvas.height = 20;
var ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 100, 100);

var img = document.createElement("img");
img.src = canvas.toDataURL("image/png");
document.body.appendChild(img);

It generates a red 55x20 px rectangle. But I would like to put some text inside this one.

I've tried fillText(); but no results.

Any help?

link

    
asked by anonymous 29.01.2015 / 17:16

1 answer

2

Just add this after ctx.fillRect :

ctx.fillRect(0, 0, 100, 100);
...
var message = "Mensagem"; //Define a mensagem
ctx.font = '9pt Arial'; //Define Tamanho e fonte
ctx.fillStyle = 'black'; //Define a cor
ctx.fillText(message, positionY, positionX); //Desenha a mensagem
    
29.01.2015 / 17:43