首页 > 解决方案 > 圆弧上的 d3 svg 剪贴蒙版

问题描述

有人可以向我解释如何在圆弧上使用剪贴蒙版。

解释我在做什么。我有一个圆圈,在这个圆圈上我添加了一个可以移动的弧。现在我想从左到右为这个圆圈添加一个线性渐变。但是渐变应该只在弧上看到,而不是圆本身。我也在这里找到了一种解决方案https://www.freshconsulting.com/d3-js-gradients-the-easy-way/但这不是我想要做的,因为我的渐变应该总是相同的,但只有弧应该显示它。例如像这样: 在此处输入图像描述

标签: javascriptd3.jssvg

解决方案


这就是你如何用 d3 绘制一个带有渐变填充的蒙版圆。

const svg = d3.select("body")
  .append("svg")
  .attr("width", 500)
  .attr("height", 500)

const defs = svg.append("defs")

const gradient = defs.append("linearGradient")
  .attr("id", "exampleGradient")

gradient.append("stop")
  .attr("offset", "10%")
  .attr("stop-color", "white")

gradient.append("stop")
  .attr("offset", "100%")
  .attr("stop-color", "red")

const mask = defs.append("mask")
  .attr("id", "donutMask")

mask.append("circle")
  .attr("cx", 250)
  .attr("cy", 250)
  .attr("r", 150)
  .attr("fill", "white")

mask.append("circle")
  .attr("cx", 250)
  .attr("cy", 250)
  .attr("r", 120)

const circle = svg.append("circle")
  .attr("r", 149)
  .attr("cx", 250)
  .attr("cy", 250)
  .attr("stroke", "black")
  .attr("mask", "url(#donutMask)")
  .attr("fill", "url(#exampleGradient)")
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>


推荐阅读