Is it possible to write text on HTML5 canvas
?
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.
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.
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>
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With