node.js - 修剪画布文本以适合
问题描述
我需要修剪一些文本以确保它适合但是,一旦我应用字体,我就会因为大小的变化而苦苦挣扎,我真的不知道如何继续下去,通过以下代码我确定了我想要的最大宽度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);
解决方案
我们可以遍历有问题的单词,减小它的大小(修剪),直到它达到我们的最大值。
下面的示例代码:
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">
推荐阅读
- angular - 如何隐藏电子默认菜单
- python - 从传感器读取方波信号
- ios - SwiftUI - 有没有办法在没有 NavigationView 的情况下构建动态列表视图?
- oracle - 尝试执行 for 循环以查找“前十个数字的总和”时遇到错误“'(' expected”
- sql-server - 使用 MS 任务计划程序每 15 分钟自动将数据从 Excel 导入 SQL Server
- sql - 如何在 postgresql jsonb 搜索中使用 SIMILAR TO 子句获取不区分大小写的数据?
- c++ - 现代 C++ 使内存泄漏更难发现
- sql - WHERE 子句中的 SQL Server CASE 表达式以检查 NULL 值
- excel - 将两行相加并将其粘贴到另一列的工作簿中
- flutter - 编写这样的代码有什么好处?