【问题标题】:SVG manipulation in ReactReact 中的 SVG 操作
【发布时间】:2017-10-07 14:09:13
【问题描述】:

我正在尝试在 SVG 中创建一个简单的图形,以显示一条线上的设备。该设备下方应有标签。我希望标签不重叠: example image .由于我使用的是 React,我想在 render() 函数中以 JSX 语法编写 SVG 代码。因此,为简单起见,假设我只有:

装备类

const Equipment = (props) => (
    <g>
        <rect
          x={props.x}
          y={props.y}
          width={props.width}
          height={props.height}
          fill={black}
        />
        <text
          x={props.x}
          y={props.y}
          fill={black}
          fontSize={props.size}
        >
            {props.text}
        </text>
    </g>
);

export default Equipment;

SVG 主类

import Equipment from './Equipment';

const SVG = (props) => (
    <svg
      width='100%'
      height='100%'
    >
        <g transform={`matrix(${props.matrix})`}>
            <Equipment
              x={10}
              y={10}
              width={100}
              height={100}
              fontSize={props.size}
              test='Equipment 1'
            />
            <Equipment
              x={60}
              y={10}
              width={50}
              height={100}
              fontSize={props.size}
              test='Equipment 2'
            />
        </g>
    </svg>
);

export default SVG;

我使用转换矩阵来缩放 SVG 中的所有内容,但将文本的大小保持为某个恒定的逆矩阵以在矩阵中缩放。

  1. 如何确保标签不重叠?
  2. 是否有声明方式或者我必须使用 while 循环?

注意:当手动创建 SVG 对象并使用诸如 checkIntersectiongetIntersectionList 之类的 SVG 函数时,这当然可以轻松完成,但这些在 React 组件上不可用,我想保留 JSX 语法.

【问题讨论】:

    标签: javascript reactjs svg jsx


    【解决方案1】:

    考虑添加一个 props,例如 textPositionY,指示文本的垂直位置。也是一个根据 SVG 元素的索引生成此位置的函数。像这样:

     {
       svgArray.map((eachSVG, index) => {
          const pxFromTop = 20;
          const generateTextPositionY = ix => fixedPosition + ix * pxFromTop;
          const currentTextPositionY = generateTextPositionY(index);
          const svgKey = `svgKey-${index}`
    
          return (
            <YourSVGComponent
              key={svgKey}
              textPositionY={currentTextPositionY}
              ...your other props
            />
       )})
     }
    

    接下来,您可以使用此道具设置文本的样式,因为您知道每个文本距顶部有多少 px。

    【讨论】:

      猜你喜欢
      • 2021-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2019-10-05
      • 2020-05-20
      • 1970-01-01
      相关资源
      最近更新 更多