I would like to be able to center single lines of text within rectangular areas I can calculate. The one thing I have expected to do in 2D geometry on a canvas is to center something whose width is unknown to you.
I have heard as a workaround that you can create the text in an HTML container and then call jQuery's width()
function, but I ?didn't correctly handle the momentary addition to the document's body? and got a width of 0.
If I have a single line of text, significantly shorter than would fill most of the width in a screen, how can I tell how wide it will be on a canvas at a font size I know?
textAlign = "center"; Which should put a text centered both vertically and horizontally.
To vertically align text with HTML5 Canvas, we can use the textBaseline property of the canvas context. textBaseline can be set with one of the following values: top, hanging, middle, alphabetic, ideographic, and bottom. Unless otherwise specified, the textBaseline property is defaulted to alphabetic.
The canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D shapes and bitmap images.
To change the color of text created by fillText, use the fillStyle property. Similarly, to change the color of text created by strokeText, use the strokeStyle property: var canvas = document. querySelector( "#myCanvas" );
You can do this by using measureText
var canvas = document.getElementById("canvas"), ctx = canvas.getContext("2d") canvas.width = 400; canvas.height = 200; ctx.fillStyle = "#003300"; ctx.font = '20px sans-serif'; var textString = "Hello look at me!!!", textWidth = ctx.measureText(textString ).width; ctx.fillText(textString , (canvas.width/2) - (textWidth / 2), 100);
Live Demo
More elaborate demo
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