【问题标题】:Canvas change width depending on percentage complete画布根据完成百分比更改宽度
【发布时间】:2020-06-24 01:48:42
【问题描述】:

我有一个 xp 系统,我有一个人升级到多远的百分比,我创建了一个矩形。但我不知道如何根据百分比改变宽度...... 我很容易得到百分比,但我需要一种方法来编码百分比 0 = 259 的起点,而 100% 是 630

    const rectX = 259;
    const rectY = 182;
    const rectWidth = 630;
    const rectHeight = 38;
    const cornerRadius = 20;

    ctx.lineJoin = 'round';
    ctx.lineWidth = cornerRadius;
    ctx.strokeStyle = '#FF1700';
    ctx.fillStyle = '#FF1700';

    ctx.strokeRect(rectX + (cornerRadius / 2), rectY + (cornerRadius / 2), rectWidth - cornerRadius, rectHeight - cornerRadius);
    ctx.fillRect(rectX + (cornerRadius / 2), rectY + (cornerRadius / 2), rectWidth - cornerRadius, rectHeight - cornerRadius);

【问题讨论】:

    标签: node.js canvas discord.js


    【解决方案1】:

    所以据我了解,您有两个数字,从 259 开始,到 630 结束,50% 表示这两个数字之间的中点,100% 表示 630,0% 表示 259,对吗?

    如果是这样的话,那么你需要这个叫做 LERP(线性插值)的东西,

    const lerp = (start: number, end: number, percentage: number): number => {
        return (((end - start) * percentage) / 100) + start;
    };
    

    或者如果你想要 javascript,只需删除类型定义,

    它的工作方式是将你的开始标准化为 0,

    现在使用很简单:console.log(lerp(259, 630, 50))

    返回:444.5

    【讨论】:

      【解决方案2】:

      您只需将矩形的宽度乘以percentage / 100。这是您的示例代码的外观。

      const rectX = 259;
      const rectY = 182;
      const rectWidth = 630;
      const rectHeight = 38;
      const cornerRadius = 20;
      
      const scale = Math.min(1, Math.max(0, percentage / 100));
      
      ctx.lineJoin = 'round';
      ctx.lineWidth = cornerRadius;
      ctx.strokeStyle = '#FF1700';
      ctx.fillStyle = '#FF1700';
      
      ctx.strokeRect(rectX + (cornerRadius / 2), rectY + (cornerRadius / 2), rectWidth - cornerRadius, rectHeight - cornerRadius);
      ctx.fillRect(rectX + (cornerRadius / 2), rectY + (cornerRadius / 2), rectWidth * scale - cornerRadius , rectHeight - cornerRadius);
      

      当百分比为100% 时,比例为1,矩形的宽度为630。当百分比为50% 时,比例为0.5,宽度为315,依此类推。

      【讨论】:

      • 这不起作用(为了 jsfiddle 测试,我将百分比更改为 50:jsfiddle.net/robhawkes/gHCJt
      • 但是我将 rectWidth 更改为 const rectWidth = 630 * xpPercent / 100; 并且它起作用了!谢谢。
      猜你喜欢
      • 1970-01-01
      • 2012-02-15
      • 2012-12-17
      • 1970-01-01
      • 2013-09-11
      • 2023-03-03
      • 1970-01-01
      • 2017-02-28
      • 2017-06-11
      相关资源
      最近更新 更多