【问题标题】:Trim Canvas text to fit修剪画布文本以适合
【发布时间】:2020-06-23 23:30:30
【问题描述】:

我需要修剪一些文本以确保它适合但是,一旦我应用字体,我就会因为大小的变化而苦苦挣扎,我真的不知道如何继续进行,通过以下代码我确定了最大宽度我想要的是 '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.js canvas discord.js


    【解决方案1】:

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

    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">

    【讨论】:

    • 今天你在提问,明天你会回来帮助别人......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    • 2021-08-12
    • 2011-11-10
    • 1970-01-01
    • 2014-05-31
    • 2011-12-28
    相关资源
    最近更新 更多