Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write text on a HTML5 canvas element?

Tags:

html

canvas

Is it possible to write text on HTML5 canvas?

like image 678
Budda Avatar asked Sep 13 '10 02:09

Budda


People also ask

How do you add text in HTML5?

To add a text to the HTML <canvas> element, you need to use the fillText() or strokeText() methods, or you can use the combination of the two. You can also give color to your text, define the font and size, and even add gradients.

Can you use text on canvas?

Visuals make sense, but using text in canvas prints can be a powerful way to make a statement. Text is a strong design choice, especially used cleverly and combined with affordable, high-quality canvas prints.


3 Answers

var canvas = document.getElementById("my-canvas");
var context = canvas.getContext("2d");

context.fillStyle = "blue";
context.font = "bold 16px Arial";
context.fillText("Zibri", (canvas.width / 2) - 17, (canvas.height / 2) + 8);
#my-canvas {
  background: #FF0;
}
<canvas id="my-canvas" width="200" height="120"></canvas>
like image 118
Zibri Avatar answered Oct 11 '22 12:10

Zibri


Drawing text on a Canvas

Markup:

<canvas id="myCanvas" width="300" height="150"></canvas>

Script (with few different options):

<script>
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    ctx.font = 'italic 18px Arial';
    ctx.textAlign = 'center';
    ctx. textBaseline = 'middle';
    ctx.fillStyle = 'red';  // a color name or by using rgb/rgba/hex values
    ctx.fillText('Hello World!', 150, 50); // text and position
</script>

Check out the MDN documentation and this JSFiddle example.

like image 32
Lior Elrom Avatar answered Oct 11 '22 12:10

Lior Elrom


Canvas text support is actually pretty good - you can control font, size, color, horizontal alignment, vertical alignment, and you can also get text metrics to get the text width in pixels. In addition, you can also use canvas transforms to rotate, stretch and even invert text.

like image 33
Eric Rowell Avatar answered Oct 11 '22 11:10

Eric Rowell