Просмотр исходного кода

fix(mini-charts): 修复图表在高分屏设备上显示模糊和位置偏移问题

通过调整 Canvas 物理像素尺寸和 u-charts 配置参数,解决图表在高 DPI 设备上的显示问题:

- 设置 Canvas 物理像素 = 逻辑像素 × pixelRatio,确保高分屏有足够像素
- 传入 u-charts 的 width/height 使用物理像素尺寸
- 将 pixelRatio 设为 1,避免 u-charts 内部双重缩放

问题原因:
1. 之前 canvas.width 和传入 u-charts 的 width 不匹配,导致坐标系统错乱
2. u-charts 使用 pixelRatio 缩放内部元素,但 canvas 缓冲区尺寸未正确设置

修复后效果:
- 图表在 2x/3x 屏幕上清晰锐利
- 图表位置正确,不会挤在左上角

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
yourname 1 неделя назад
Родитель
Сommit
508b196a23
1 измененных файлов с 19 добавлено и 7 удалено
  1. 19 7
      mini-ui-packages/mini-charts/src/components/BaseChart.tsx

+ 19 - 7
mini-ui-packages/mini-charts/src/components/BaseChart.tsx

@@ -104,21 +104,33 @@ const BaseChartInner: React.FC<BaseChartProps> = (props) => {
           const canvas = res[0].node;
           const ctx = canvas.getContext('2d');
 
-          console.debug('[BaseChartOriginal2D] canvas.width', canvas.width);
-          console.debug('[BaseChartOriginal2D] canvas.height', canvas.height);
-
           // 将 Taro CanvasContext 转换为 uCharts 需要的 CanvasContext
           const extendedCtx = ctx as ExtendedCanvasContext;
 
-          // Canvas 2D: 使用 canvas 的实际 width/height
-          // 基础配置
+          // 获取设备像素比,用于高清屏适配
+          const pixelRatio = sysInfo.pixelRatio || 1;
+          console.debug('[BaseChart] pixelRatio', pixelRatio);
+          console.debug('[BaseChart] CSS 宽度 cw (逻辑像素)', cw);
+          console.debug('[BaseChart] CSS 高度 ch (逻辑像素)', ch);
+
+          // 方案 A:设置 Canvas 物理像素 = 逻辑像素 × pixelRatio
+          // 这样在高分屏上有足够的物理像素,图表更清晰
+          const physicalWidth = cw * pixelRatio;
+          const physicalHeight = ch * pixelRatio;
+          canvas.width = physicalWidth;
+          canvas.height = physicalHeight;
+          console.debug('[BaseChart] 设置后 canvas.width (物理像素)', canvas.width);
+          console.debug('[BaseChart] 设置后 canvas.height (物理像素)', canvas.height);
+
+          // u-charts 接收物理像素尺寸,pixelRatio 设为 1 避免双重缩放
           const chartConfig: ChartsConfig = {
             type,
             context: extendedCtx,
             categories,
             series,
-            width: canvas.width,
-            height: canvas.height,
+            width: physicalWidth,  // 物理像素(等于 canvas.width)
+            height: physicalHeight, // 物理像素(等于 canvas.height)
+            pixelRatio: 1,  // 设为 1,让 u-charts 知道这是最终物理像素
             animation: true,
             background: '#FFFFFF',
             color: ['#3b82f6', '#10b981', '#f59e0b', '#8b5cf6', '#ef4444'],