<circle> 是SVG中用来绘制圆形的元素。通过设置圆心的坐标(cxcy)以及圆的半径(r),可以绘制出不同大小、位置的圆形。<circle> 元素还支持多个属性来自定义圆的外观,如填充颜色、边框颜色等。

目录

  1. 基本语法
  2. 属性详解
  3. 示例代码
  4. 参考资料
  5. 出站链接

基本语法

<circle cx="圆心X" cy="圆心Y" r="半径" fill="填充颜色" stroke="描边颜色" stroke-width="描边宽度" />

  • cx:圆心的X坐标,表示圆的中心在水平轴上的位置。
  • cy:圆心的Y坐标,表示圆的中心在垂直轴上的位置。
  • r:圆的半径,决定了圆的大小。
  • fill:圆的填充颜色。
  • stroke:圆的边框颜色。
  • stroke-width:圆的边框宽度,单位为像素。

属性详解

  • cx 和 cy
    • 控制圆心的位置。默认值为cx="0"cy="0",即圆心位于坐标系的原点。
  • r
    • 控制圆的半径,决定圆的大小。默认值为r="0",即没有圆形。
  • fill
    • 用于设置圆形的填充颜色。可以使用颜色名称(如red),十六进制颜色值(如#ff0000),RGB(如rgb(255,0,0))等格式。
  • stroke
    • 用于设置圆形边框的颜色。支持与fill相同的颜色格式。例如,stroke="black"
  • stroke-width
    • 控制圆形边框的宽度,单位为像素。如果没有设置,默认值为0,即没有边框。

示例代码

  1. 基本圆形
<svg width="200" height="200">
  <circle cx="100" cy="100" r="80" fill="blue" stroke="black" stroke-width="3" />
</svg>

  • 这个例子绘制了一个蓝色填充、黑色边框的圆形,圆心位于(100, 100),半径为80。
  1. 没有边框的圆形
<svg width="200" height="200">
  <circle cx="100" cy="100" r="50" fill="green" />
</svg>

  • 这个例子绘制了一个绿色填充、没有边框的圆形,圆心位于(100, 100),半径为50。
  1. 渐变填充的圆形
<svg width="200" height="200">
  <defs>
    <radialGradient id="grad1" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
      <stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" />
      <stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
    </radialGradient>
  </defs>
  <circle cx="100" cy="100" r="80" fill="url(#grad1)" stroke="black" stroke-width="3" />
</svg>

  • 这个例子展示了一个圆形,填充了从黄色到红色的径向渐变。
  1. 动态圆形
<svg width="200" height="200">
  <circle id="animateCircle" cx="100" cy="100" r="40" fill="blue" />
  <animate
    xlink:href="#animateCircle"
    attributeName="r"
    from="40"
    to="80"
    dur="2s"
    repeatCount="indefinite"
  />
</svg>

  • 这个例子展示了一个动态圆形,圆的半径从40变化到80,动画循环进行。
  1. 圆形与鼠标交互
<svg width="200" height="200">
  <circle id="hoverCircle" cx="100" cy="100" r="50" fill="red" />
  <script>
    document.getElementById('hoverCircle').addEventListener('mouseover', function() {
      this.setAttribute('fill', 'green');
    });
    document.getElementById('hoverCircle').addEventListener('mouseout', function() {
      this.setAttribute('fill', 'red');
    });
  </script>
</svg>

  • 这个例子展示了一个圆形,当鼠标悬停时圆的颜色从红色变为绿色。

参考资料

出站链接

<circle>元素是SVG图形中常见且重要的一部分,广泛用于图标、图表以及各种图形设计中。通过控制圆心、半径、填充和边框属性,开发者可以创建出富有表现力和动态效果的圆形元素。