Writing in Rectangle - HTML Canvas

Asked

Viewed 1,614 times

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 a text within this.

I tried to fillText(); but with no results.

Some help ?

http://jsfiddle.net/frvfyfbL/1/

1 answer

2


Just add this after the 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.