Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center (proportional font) text in an HTML5 canvas

Tags:

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?

like image 708
Christos Hayward Avatar asked Dec 07 '12 21:12

Christos Hayward


People also ask

How do I center text in a canvas in HTML?

textAlign = "center"; Which should put a text centered both vertically and horizontally.

How do I vertically align text in canvas?

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.

Does HTML5 support canvas element?

The canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D shapes and bitmap images.

How do I change text color in canvas HTML?

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" );


1 Answers

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

like image 197
Loktar Avatar answered Nov 09 '22 05:11

Loktar