首页 > 解决方案 > 修剪画布文本以适合

问题描述

我需要修剪一些文本以确保它适合但是,一旦我应用字体,我就会因为大小的变化而苦苦挣扎,我真的不知道如何继续下去,通过以下代码我确定了我想要的最大宽度to have 是 '363' 并且如果它超过 363(这是 'w' 最多应该等于的值)修剪变量并添加省略号。否则,如果有人的用户名超过 363 并应用了字体和大小,它会重叠并离开屏幕,如图所示。如何做到这一点?代码:

let userGrab = message.author.username;

    function drawUsername(x, y, use, dis) {
      ctx.font = '34px Shapirit';
      ctx.fillStyle = '#FFFFFF';
      ctx.textAlign = 'left';
      ctx.strokeStyle = 'black';
      ctx.lineWidth = 0.5;
      ctx.fillText(use, x, y);
      ctx.strokeText(use, x, y);
      w = ctx.measureText(use).width;

      ctx.font = '22px Shapirit';
      ctx.fillStyle = '#7F8384';
      ctx.textAlign = 'left';
      ctx.strokeStyle = 'black';
      ctx.lineWidth = 0.25;
      ctx.fillText(dis, x + w + 4, y);
      ctx.strokeText(dis, x + w + 4, y);
    }

    drawUsername(270, 165.4, usergrab, discrim);

长用户名: 长用户

标签: node.jscanvasdiscord.js

解决方案


我们可以遍历有问题的单词,减小它的大小(修剪),直到它达到我们的最大值。
下面的示例代码:

canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");

function drawUsername(x, y, max, use, dis) {
  ctx.font = '34px Shapirit';
  ctx.lineWidth = 0.5;
  while (ctx.measureText(use).width > max) {
    use = use.substring(0, use.length-1);
  }
  ctx.fillText(use, x, y);
  ctx.strokeText(use, x, y);
  w = ctx.measureText(use).width
  

  ctx.font = '22px Shapirit';
  ctx.lineWidth = 0.25;
  ctx.fillText(dis, x + w + 4, y);
  ctx.strokeText(dis, x + w + 4, y);
}

drawUsername(20, 20, 150, "wwwwwwwwowowow", "123");
<canvas id="canvas">


推荐阅读