首页 > 解决方案 > ClipPath 隐藏原始形状 - d3 ReactJS

问题描述

我是 D3 和 ReactJS 的新手,试图用直线剪圆,但不知道它是如何工作的。我有这个 HTML 代码来绘制图像;

  <div >

          <svg xmlns="http://www.w3.org/2000/svg" version="1.1"  className="clip-path" ref={this.attachCircle.bind(this)}>

          </svg>
        </div>

这是我绘制图像的功能;

attachCircle = (svgRef:SVGElement) => {

const svg = d3.select(svgRef);
// draw a circle

  svg.append("circle")            // shape it as an ellipse
    .attr("cx", 100)            // position the x-centre
    .attr("cy", 80)            // position the y-centre
    .attr("r", 80)            // set the x radius
        .attr("fill", "SteelBlue")
}

结果是这样的;

在此处输入图像描述

但是一旦我加入clipPath圈子;

svg.append("clipPath")       // define a clip path
    .attr("id", "clip") // give the clipPath an ID
  .append("circle")            // shape it as an ellipse
    .attr("cx", 100)            // position the x-centre
    .attr("cy", 80)            // position the y-centre
    .attr("r", 80)            // set the x radius
        .attr("fill", "SteelBlue")

它在屏幕上什么也不显示。它没有画任何圆圈或任何东西。

谁能解释为什么会这样??或者我错过了什么?

标签: javascriptreactjsd3.js

解决方案


你需要使用use

 <use clip-path="url(#clip)" xlink:href="#clip" fill="red" />

https://developer.mozilla.org/en-US/docs/Web/SVG/Element/clipPath


推荐阅读