JSFiddle - React, Tailwind, and code Playground

by m1erickson

HTML

<div>Testing...</div>

CSS

body {
            background-color: ivory;
            padding:50px;
        }

JavaScript

var canvas = document.createElement("canvas");
        canvas.width = 1000;
        canvas.height = 50;
        var ctx = canvas.getContext("2d");

        function measureTextHeight(left, top, width, height, text) {

            // Draw the text in the specified area
            ctx.save();
            ctx.clearRect(0, 0, 300, 50);
            ctx.fillText(text, 0, 35);
            ctx.restore();

            // Get the pixel data from the canvas
            var data = ctx.getImageData(left, top, width, height).data,
                first = false,
                last = false,
                r = height,
                c = 0;

            // Find the last line with a non-white pixel
            while (!last && r) {
                r--;
                for (c = 0; c < width; c++) {
                    if (data[r * width * 4 + c * 4 + 3]) {
                        last = r;
                        break;
                    }
                }
            }

            // Find the first line with a non-white pixel
            while (r) {
                r--;
                for (c = 0; c < width; c++) {
                    if (data[r * width * 4 + c * 4 + 3]) {
                        first = r;
                        break;
                    }
                }

                // If we've got it then return the height
                if (first != r) return last - first;
            }
            return 0; // epic fail if we get here :(
        }

        ctx.font = '32px Arial';
        var start = new Date().getTime();
        var text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        for (var x = 0; x < 1000; x++) {
            var height = measureTextHeight(0, 0, 50, 50, text);
        }
        alert("I get: " + measureTextHeight(0, 0, 50, 50, text) + "pixels high repeated 1000 times in " + (new Date().getTime() - start) + "ms");