Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

calculate width of text javascript

function measureText(str, fontSize = 10) {
  const widths = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.2796875,0.2765625,0.3546875,0.5546875,0.5546875,0.8890625,0.665625,0.190625,0.3328125,0.3328125,0.3890625,0.5828125,0.2765625,0.3328125,0.2765625,0.3015625,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.2765625,0.2765625,0.584375,0.5828125,0.584375,0.5546875,1.0140625,0.665625,0.665625,0.721875,0.721875,0.665625,0.609375,0.7765625,0.721875,0.2765625,0.5,0.665625,0.5546875,0.8328125,0.721875,0.7765625,0.665625,0.7765625,0.721875,0.665625,0.609375,0.721875,0.665625,0.94375,0.665625,0.665625,0.609375,0.2765625,0.3546875,0.2765625,0.4765625,0.5546875,0.3328125,0.5546875,0.5546875,0.5,0.5546875,0.5546875,0.2765625,0.5546875,0.5546875,0.221875,0.240625,0.5,0.221875,0.8328125,0.5546875,0.5546875,0.5546875,0.5546875,0.3328125,0.5,0.2765625,0.5546875,0.5,0.721875,0.5,0.5,0.5,0.3546875,0.259375,0.353125,0.5890625]
  const avg = 0.5279276315789471
  return str
    .split('')
    .map(c => c.charCodeAt(0) < widths.length ? widths[c.charCodeAt(0)] : avg)
    .reduce((cur, acc) => acc + cur) * fontSize
}
console.log(measureText("Hello world")); // Output: 49.40625000000001
console.log(measureText("This is a long text")); // Output: 77.74999999999999
console.log(measureText("i")); // Output: 2.21875
Comment

PREVIOUS NEXT
Code Example
Javascript :: node js load css file 
Javascript :: react fragment 
Javascript :: foreach javascript arrow function 
Javascript :: push an property and value to an object in javascript 
Javascript :: create a solid.js project 
Javascript :: set node_env 
Javascript :: get form data as object jquery 
Javascript :: run a while loop for certain time javascript 
Javascript :: get Two digit number js 
Javascript :: object get array of values 
Javascript :: why is my deleteOne mongoose middleware not working 
Javascript :: jquery select dropdown option 
Javascript :: number format currency 
Javascript :: jquery li count in ul 
Javascript :: date add hours javascript 
Javascript :: count array filter javascript 
Javascript :: axios cancel request 
Javascript :: lodash pick 
Javascript :: Toggle checkbox checking in jquery 
Javascript :: json example 
Javascript :: action checkbox selected vue js 
Javascript :: react native environment variables 
Javascript :: .join in javascript 
Javascript :: javascript calculate aspect ratio 
Javascript :: jquery set textbox value 
Javascript :: how to make a clock in js 
Javascript :: updateone mongoose example 
Javascript :: javascript get array object by id 
Javascript :: switch js 
Javascript :: how to check if all inputs are not empty with javascript 
ADD CONTENT
Topic
Content
Source link
Name
4+2 =