SVG Defs封装 [英] Svg defs encapsulation

查看:129
本文介绍了SVG Defs封装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在末尾用箭头封装SVG线,并且在React组件中没有任何全局ID(但是问题本身与React无关).

I'm trying to encapsulate an SVG line with an arrowhead at the end without any global ids in a React component, (but the question itself has nothing to do with React).

小提琴示例 https://jsfiddle.net/wzyzqhgh/1/

const LinkComponent = ({ x1, y1, x2, y2, color }) => {
  const coordinates = calculateCoordinates(x1, y1, x2, y2)
  const linkStyle = calculateStyles(x1, y1, x2, y2)
  return (<svg style={linkStyle} shapeRendering="geometricPrecision">
    <defs>
      <marker 
        id="arrow" 
        markerWidth={10} 
        markerHeight={10} 
        refX={9} 
        refY={3} 
        orient="auto" 
        markerUnits="strokeWidth"
      >
        <path d="M0,0 L0,6 L9,3 z" fill={color} />
      </marker>
    </defs>
    <line
      x1={coordinates.x1}
      y1={coordinates.y1}
      x2={coordinates.x2}
      y2={coordinates.y2}
      strokeWidth={1}
      stroke={color}
      markerEnd="url(#arrow)"
    />
  </svg>)
}

此组件每次渲染时都会在本地定义一个marker,但似乎markerid是全局的.所以当我这样做时:

This component defines a marker locally each time it's rendered, but seems like the id of the marker is global. So when I do this:

ReactDom.render(
  (<div>
    <LinkComponent x1={10} y1={20} x2={100} y2={200} color="red" />
    <LinkComponent x1={10} y1={200} x2={200} y2={10} color="blue" />
  </div>),
  document.getElementById('test')
)

两个组件marker-end中都使用了第一种颜色.

The first color is used in both components marker-end.

问题:如何将marker封装在单个svg元素中,以免泄漏?除了id,还有其他方法可以在marker-*属性中引用它们吗?如果不可能,如何在不使用defs/marker s

Question: How do I encapsulate markers in a single svg element so they don't leak out? Is there any other way to reference them in marker-* properties than id? If it's not possible, how can I achieve similar effects without using defs/markers

推荐答案

您有几种选择:

  1. 将标记定义拉出为所有LinkComponent引用的静态SVG,或者

  1. Pull the marker definition(s) out into a static SVG that is referenced by all LinkComponents, or

每次都生成一个随机的唯一id.

Generate a random, unique id each time.

将颜色添加到ID中,因此即使您有重复的标记定义,引用哪个也没关系:

Add the colour to the id, so even if you have duplicate marker definitions, it doesn't matter which one is referenced:

id="arrow-{color}"

  • 不使用标记.自己绘制箭头.

  • Don't use markers. Draw the arrowhead yourself.

    这篇关于SVG Defs封装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆