Svg Circle填充CSS

时间:2014-11-05 07:28:35

标签: javascript css css3 svg

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

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

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

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

enter image description here

2 个答案:

答案 0 :(得分:1)

这是你想要的吗? 希望它有所帮助!

var svg = d3.select('body').append('svg')
.attr('class', 'chart')
.attr('width', 300)
.attr('height', 300)
.append('g')
.attr('transform', 'translate(100, 100)');

svg.append('g')
.append('circle')
.attr('r', 30)
.style('stroke', 'red')
.style('stroke-width', '6px')
.style('fill', 'red')
.style('fill-opacity', 0)
;

fiddle

答案 1 :(得分:1)

从评论中修改:
因为我还没有找到如何应用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>
&#13;
&#13;
&#13;