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

Stencil集成Puppeteer截图测试文本与字体渲染不稳定问题

解决Stencil e2e截图测试中文本渲染不稳定的方案

针对你遇到的文本时隐时现的问题,可通过以下步骤实现稳定渲染:

1. 等待字体完全加载

字体异步加载是导致截图时机不对的核心原因之一,可通过Puppeteer的waitForFunction等待字体加载完成:

await page.waitForFunction(() => {
  return document.fonts.check('16px "Source Sans 3"');
});

2. 固定视口尺寸

Docker环境下Chromium的默认视口可能不稳定,提前设置固定视口避免布局偏移:

const page = await newE2EPage();
await page.setViewport({ width: 1200, height: 800 }); // 根据组件实际尺寸调整
await page.setContent(html);

3. 全局禁用动画与过渡

组件的动画/过渡效果可能导致截图时元素状态不一致,添加全局样式禁用:

await page.addStyleTag({
  content: `
    @font-face {
      font-family: "Source Sans 3";
      src: url("${getAssetPath("../assets/fonts/SourceSans3-VariableFont_wght.ttf")}");
      font-weight: 100 900;
    }

    body {
      -webkit-font-smoothing: antialiased;
    }

    /* 新增:禁用所有动画和过渡 */
    * {
      animation: none !important;
      transition: none !important;
    }
  `,
});

4. 等待组件完全渲染

Stencil组件存在异步渲染周期,需等待组件就绪后再截图:

// 等待所有nl-button组件加载完成
await page.waitForSelector('nl-button', { timeout: 5000 });
// 或者等待组件内部文本节点渲染完成
await page.waitForFunction(() => {
  return Array.from(document.querySelectorAll('nl-button')).every(btn => btn.textContent.trim() !== '');
});

5. 优化Chromium启动参数

在Stencil配置中添加更多稳定渲染的启动参数:

// stencil.config.ts中配置e2e选项
export const config: Config = {
  e2e: {
    // ...其他配置
    puppeteer: {
      launchOptions: {
        args: [
          '--font-render-hinting=none',
          '--disable-gpu',
          '--disable-dev-shm-usage',
          '--no-sandbox',
          '--disable-font-subpixel-positioning',
          '--disable-background-timer-throttling'
        ]
      }
    }
  }
};

6. 预加载字体文件

将字体预加载逻辑提前到页面初始化阶段,避免动态添加@font-face的延迟:

const html = `
  <head>
    <link rel="preload" href="${getAssetPath("../assets/fonts/SourceSans3-VariableFont_wght.ttf")}" as="font" type="font/ttf" crossorigin>
  </head>
  ${componentStatesTemplate}
`;
await page.setContent(html);

内容的提问来源于stack exchange,提问作者Semyon Volkov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 17:45:28