String metrics in canvas :
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
var txt = "Hello World"
ctx.fillText("width:" + ctx.measureText(txt).width, 10, 50)
ctx.fillText(txt, 10, 100);
HTML canvas measureText() Method I can only take the width.
I was able to insert
in SVG, but it doesnât seem to be possible in canvas
- English multi-line display
- https://codepen.io/nishiohirokazu/pen/jjNyye
- Weâre chopping it up by the word and measuring metrics.
There is a possible breakable:0/1 attribute between the letters.
- For now, Iâll just target Japanese and set everything to 1.
lineheight
If you write 333 with point 0,0 and size:100 and getBounds
- ctx.measureText(â333â)
- TextMetrics {width: 166.845703125}
- window.x.textItem.getBounds()
- Rectangle {_x: -98.54999542236328, _y: -50, _width: 197.09999084472656, _height: 120, _owner: PointText, âŠ} â33.â
- textItem.getBounds()
- Rectangle {_x: -98.54999542236328, _y: -50, _width: 131.39999389648438, _height: 120, _owner: PointText, âŠ}
- ctx.measureText(â33â)
- TextMetrics {width: 111.23046875}
paper.getBounds.height is simply fontsize * 1.2
This page is auto-translated from /nishio/ä»çźăźèȘćăă©ăłăă”ă€ășèȘżæŽ using DeepL. If you looks something interesting but the auto-translated English is not good enough to understand it, feel free to let me know at @nishio_en. Iâm very happy to spread my thought to non-Japanese readers.