javascript - measure text size on html canvas element
JavaScript[Edit]
+
0
-
0
JavaScript - measure text size on HTML canvas element
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21const measureText = (context, text) => { const metrics = context.measureText(text); return { width: metrics.width, height: metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent // it measures text height according to currently used characters }; }; // Usage example: const canvas = document.createElement('canvas'); const context = canvas.getContext('2d'); context.font = '10px serif'; const size = measureText(context, 'Hello, World!'); console.log('text width: ' + size.width + 'px'); console.log('text height: ' + size.height + 'px');
Reset
[Edit]
+
0
-
0
JavaScript - measure text size on HTML canvas element
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17const measureText = (context, text) => { const metrics = context.measureText(text); return { width: metrics.width, height: metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent // it measures text height according to currently used characters }; }; // Usage example: const context = ... context.font = '10px serif'; const {width, height} = measureText(context, 'Hello, World!');