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

使用@react-sigma-core渲染CustomImageNode及解决SVG裁剪问题

解决@react-sigma-core中SVG节点图片被裁剪的问题

一、先检查SVG的 viewBox 属性

默认的NodeImageProgram会按节点size缩放图片,但如果SVG没设置viewBox,很容易被裁剪。给你的SVG加上正确的viewBox,比如:

<svg viewBox="0 0 100 100" ...>...</svg>

这个属性能让SVG自适应节点尺寸,避免被裁切。

二、调整节点和Sigma配置

  1. 删掉cameraSettings.ratio:你配置里的cameraSettings: { ratio: 0.5 }会缩放整个画布,大概率是导致图片显示异常的原因,先去掉试试。
  2. 调大scale参数:当前scale: 0.09太小了,改成0.5左右,再配合节点size调整,看图片能不能完整显示。
  3. 给节点加imageRatio:如果SVG是固定宽高比,在节点数据里加这个属性,让Sigma按比例适配:
graph.addNode(`${svg.x}.${svg.y}`, {
  x: svg.x + 50,
  y: svg.y + 30,
  size: 50,
  color: 'white',
  image: svgToDataURI(svg.val),
  type: 'image',
  imageRatio: 1, // 正方形设1,宽高2:1就设2,根据你的SVG来
});

三、自定义图片渲染节点实现

如果默认的NodeImageProgram还是不行,就自己写个自定义渲染类,步骤如下:

  1. 写自定义节点渲染类:
import { NodeProgram, RenderParams } from '@react-sigma/core';

class CustomImageNodeProgram extends NodeProgram {
  constructor(gl: WebGLRenderingContext) {
    super(gl, `
      precision mediump float;
      attribute vec2 a_position;
      attribute vec2 a_size;
      attribute vec4 a_color;
      attribute vec2 a_imageCoord;
      uniform vec2 u_resolution;
      uniform sampler2D u_texture;
      varying vec2 v_imageCoord;
      varying vec4 v_color;

      void main() {
        vec2 position = (a_position / u_resolution) * 2.0 - 1.0;
        vec2 size = (a_size / u_resolution) * 2.0;
        gl_Position = vec4(position, 0.0, 1.0);
        gl_PointSize = max(a_size.x, a_size.y);
        v_imageCoord = a_imageCoord;
        v_color = a_color;
      }
    `, `
      precision mediump float;
      varying vec2 v_imageCoord;
      varying vec4 v_color;
      uniform sampler2D u_texture;

      void main() {
        vec4 textureColor = texture2D(u_texture, v_imageCoord);
        gl_FragColor = textureColor * v_color;
      }
    `);
  }

  process(params: RenderParams) {
    const { nodes } = params;
    const imageCoords = this.attributes.a_imageCoord;
    nodes.forEach((node, index) => {
      // 设置完整的图片坐标范围,确保整张图都能被绘制
      imageCoords.set(index * 2, 0);
      imageCoords.set(index * 2 + 1, 0);
      imageCoords.set(index * 2 + 2, 1);
      imageCoords.set(index * 2 + 3, 1);
    });
    super.process(params);
  }
}
  1. 在Sigma配置里替换默认的渲染类:
const sigmaSettings = {
  // ... 其他原有配置
  nodeProgramClasses: {
    image: CustomImageNodeProgram, // 换成自定义的类
  },
};
  1. 确认节点的image是有效的Data URI,而且SVG已经加了正确的viewBox。

四、调试技巧

  • 用浏览器开发者工具看SVG实际渲染的尺寸,检查有没有额外的CSS导致裁剪。
  • 先关掉scale和cameraSettings这些缩放配置,一步步排查到底是哪个参数出问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 17:55:15