Answer the question
In order to leave comments, you need to log in
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;
}
innerIFLength(this);
function innerIFLength(self) {
if ( self.resizeDiv.getBoundingClientRect().width > maxWidth ) {
text = text.slice(0, -1);
self.resizeDiv.innerText = text;
innerIFLength(self);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question