html canvas text overflow ellipsis

canvas, html5-canvas

Solution

There is no standard function.

As I needed one, I made this small function that computes the best fitting string :

function fittingString(c, str, maxWidth) {
  var width = c.measureText(str).width;
  var ellipsis = '…';
  var ellipsisWidth = c.measureText(ellipsis).width;
  if (width<=maxWidth || width<=ellipsisWidth) {
    return str;
  } else {
    var len = str.length;
    while (width>=maxWidth-ellipsisWidth && len-->0) {
      str = str.substring(0, len);
      width = c.measureText(str).width;
    }
    return str+ellipsis;
  }
}

where `c` is the 2D context.

You can draw the string normally after having set your font and other drawing parameters of your canvas :

c.fillText(fittingString(c, "A big string that will likely be truncated", 100), 50, 50);

Problem

Is it possible to draw text on a canvas that has an ellipsis at the end of the text if the text won't fit in the available width and needs to be truncated? Thanks.

Original source