L
L
liltrill2019-10-24 21:27:31
css
liltrill, 2019-10-24 21:27:31

What is the best way to do text cropping in js?

You need to crop the text if it does not fit into the area. The user enters the text himself and the input changes the width from its content, so I would like to know how best to find out the size of the line, more precisely, so which one is faster?
1 way:

innerIFLength(this);
function innerIFLength(self) {
     if ( self.getTextWidth(text) > maxWidth ) {
          text = text.slice(0, -1);
          innerIFLength(self);
     }
}

getTextWidth(text) {
     let canvas = document.createElement("canvas"),
          context = canvas.getContext("2d");

          context.font="17px Roboto";

          return context.measureText(text).width;
}

Method 2:
To animate the input, use a div that is hidden, and you can do this:
innerIFLength(this);
function innerIFLength(self) {
     if ( self.resizeDiv.getBoundingClientRect().width > maxWidth ) {
     
          text = text.slice(0, -1);
          self.resizeDiv.innerText = text;
          innerIFLength(self);
     }
}

What's faster? And how can you make a normal benchmark?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
SerzN1, 2018-09-03
@SerzN1

`overflow: hidden;`
https://jsfiddle.net/dejcnuz0/2/

A
Anton Anton, 2019-10-24
@liltrill

Well for tests there is https://jsperf.com/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question