javascript - Svg 圆形填充 CSS

标签 javascript css svg

可能是一个相对简单的问题,但我找不到答案:

是否可以在一定程度上(具有特定半径)用颜色填充圆? 或者有 2 条边框线 - 一条是彩色的,一条是白色的,带有填充色?

style="fill:steelblue; stroke-width: 2px; stroke: #8cc63f;"

我希望在此 fiddle 中实现类似(或类似)的目标:

enter image description here

最佳答案

根据评论编辑:
由于我没有找到如何将 css "background-image"应用于 circle 元素,所以我添加了一种使用 js 的方法。

或者您可以使用 gradients 实现此目的尤其是 radial-gradients :

var svg = document.querySelectorAll('svg')[0],
  r = 30,
  cy = 60,
  nr = r - (r * 0.7),
  c1 = document.querySelectorAll('circle')[0],
  //Assuming you already have those ones

  //first make a copy of the circle you just made
  c2 = c1.cloneNode();

//then apply new styles to the first circle
c1.setAttributeNS(null, "fill", "transparent");
c1.style.stroke = "#8cc63f";
c1.style.strokeWidth = "2px";
c1.parentNode.appendChild(c2);

//and to the new one
c2.setAttributeNS(null, "fill", "red");
c2.style.strokeWidth = "0";
c2.r.baseVal.value = r - nr; //change its radius

//Wrap thoe elements into a single g that will act as one element
var g = document.createElementNS("http://www.w3.org/2000/svg", 'g');
g.appendChild(c2);
g.appendChild(c1);
svg.appendChild(g)
<svg width="720" height="120">
  <defs>
    <radialGradient id="gradient">
      <stop offset="0%" stop-color="red" />
      <stop offset="70%" stop-color="red" />
      <stop offset="71%" stop-color="transparent" />
    </radialGradient>
  </defs>
  <circle cx="40" cy="60" r="30"></circle>
  <circle cx="120" cy="60" r="30" style="fill:url(#gradient); stroke-width: 2px; stroke: #8cc63f;"></circle>
</svg>

关于javascript - Svg 圆形填充 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26751782/

相关文章:

javascript - 相对于鼠标位置从其中心缩放图像

javascript - 在 d3js 的热图网格中附加文本或圆圈

android - 从 SVG 设置图层列表项

javascript - Facebook Graph API 返回缺少数据的对象

javascript - onclick 将多个 div 作为图像保存到一个 zip 文件中

javascript - 达到限制后使数字变量不可变

html - Weasyprint pdf 不适合页面

animation - 在 SVG 中定义圆/弧动画

javascript - 如何去除此处的透明度

javascript - 如何在 angularjs 中使用 Controller 内部的 Promise?