You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PIXI.js文本在Redux状态更新时偏移至左上角的修复方案

修复PIXI文本在Redux状态更新后位置偏移的问题

问题原因

PIXI.Text的text属性更新后,其width和height不会立即同步更新——这些尺寸是在PIXI的渲染周期中异步计算的。当Redux状态触发回调调用setWinAmountText时,直接读取this.winAmountText.width拿到的是旧值,导致计算出的x坐标错误,最终文本偏移到左上角。

修复方案

方案1:强制更新文本尺寸

修改setWinAmountText方法,在更新文本内容后手动调用updateText(),强制PIXI立即重新计算文本尺寸:

private setWinAmountText(value: number) {
    this.winAmountText.text = value.toString();
    // 强制更新文本布局,确保width/height为最新值
    this.winAmountText.updateText();
    this.winAmountText.x = this.width * 0.56 - this.winAmountText.width;
    this.winAmountText.y = this.height * 0.905;
}

方案2:延迟到下一帧计算位置

如果手动更新尺寸无效,可将位置计算逻辑延迟到下一渲染帧执行,确保文本尺寸已完成更新:

import { Ticker } from 'pixi.js';

private setWinAmountText(value: number) {
    this.winAmountText.text = value.toString();
    // 在下一帧执行位置计算
    Ticker.shared.addOnce(() => {
        this.winAmountText.x = this.width * 0.56 - this.winAmountText.width;
        this.winAmountText.y = this.height * 0.905;
    });
}

方案3:利用锚点优化布局(推荐)

通过设置文本锚点,避免手动计算偏移量,从根源解决尺寸更新延迟的问题。例如要让文本右边缘对齐到this.width*0.56位置:

// 在构造函数中添加锚点设置
this.winAmountText.anchor.set(1, 0); // x锚点设为1,代表文本右边缘

// 修改setWinAmountText方法
private setWinAmountText(value: number) {
    this.winAmountText.text = value.toString();
    this.winAmountText.x = this.width * 0.56; // 直接绑定到目标位置,锚点会自动对齐
    this.winAmountText.y = this.height * 0.905;
}

内容的提问来源于stack exchange,提问作者charan vendra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 14:21:17