JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="inputController">Input:
<input ng-model="inputText" />
<div get-width class="output">{{ inputText | uppercase }}</div>
<div>Textwidth: {{ textSize }}</div>
</div>
</div>
CSS
body {
background: #233a40;
color: #fff;
font: 16px/1.8 sans-serif;
}
.container {
width: 84%;
margin:0 auto;
max-width:1140px;
}
header {
width: 100%;
margin:0px auto;
}
.output {
background: rgba(0, 0, 0, 0.2);
text-align: center;
color:#fff;
font: 95px"Arial";
}
JavaScript
var myApp = angular.module('myApp', []);
myApp.controller('inputController', ['$scope', function ($scope) {
$scope.inputText = "";
$scope.textSize = 0;
}]);
myApp.directive('getWidth', [function () {
function link(scope, element, attrs) {
console.log("scope=%s, element=%s, attrs=%s", scope, element.text(), attrs.replace);
//scope.textSize = getTextWidth(element.text(), "95px Arial");
scope.$watch(_ => getTextWidth(element[0].innerText, "95px Arial"), newVal => scope.textSize = newVal);
}
return {
restrict: 'A',
link: link
};
}]);
function getTextWidth(text, font) {
// re-use canvas object for better performance
var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
var context = canvas.getContext("2d");
context.font = font;
var metrics = context.measureText(text);
console.log("text = %s, width=%s", text, metrics.width);
return metrics.width;
}