阿里云主机折上折
  • 微信号
Current Site:Index > <svg>-SVG vector graphics

<svg>-SVG vector graphics

Author:Chuan Chen 阅读数:3404人阅读 分类: HTML

<svg> is a tag introduced in HTML5 for embedding vector graphics directly into web pages. Vector graphics do not lose quality when scaled, making them ideal for icons, charts, and similar scenarios. With SVG, developers can define paths, shapes, gradients, and other elements using XML syntax to achieve complex visual effects.

Basic Structure of <svg>

SVG graphics are defined using the <svg> tag, with basic attributes like width and height to set the canvas dimensions. Here’s a simple SVG example:

<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
  <circle cx="100" cy="100" r="50" fill="red" />
</svg>

This code draws a red circle with a radius of 50, centered at (100, 100) on the canvas. The xmlns attribute declares the SVG namespace, ensuring the browser parses it correctly.

Basic Graphic Elements

SVG provides several built-in graphic elements that can be called directly via tags:

Rectangle <rect>

<svg width="200" height="200">
  <rect x="50" y="50" width="100" height="80" fill="blue" stroke="black" stroke-width="2"/>
</svg>
  • x/y define the top-left corner coordinates
  • stroke sets the border color
  • stroke-width controls the border thickness

Circle <circle>

<circle cx="120" cy="80" r="40" fill="green" fill-opacity="0.5"/>
  • cx/cy define the center coordinates
  • fill-opacity controls fill transparency (0-1)

Ellipse <ellipse>

<ellipse cx="150" cy="100" rx="70" ry="40" fill="purple"/>
  • rx/ry control the horizontal and vertical radii, respectively

Path <path>

<path> is the most powerful SVG element, defining complex paths via the d attribute:

<svg width="300" height="200">
  <path d="M10 80 Q 150 10 290 80 T 150 150" 
        fill="none" 
        stroke="orange"
        stroke-width="3"/>
</svg>

Path command explanations:

  • M10 80: Move to coordinate (10, 80)
  • Q 150 10 290 80: Quadratic Bézier curve to (290, 80) with control point (150, 10)
  • T 150 150: Simplified quadratic Bézier curve (automatically symmetrical)

Text <text>

SVG supports embedding text directly into graphics:

<svg width="400" height="100">
  <text x="20" y="50" 
        font-family="Arial" 
        font-size="30"
        fill="steelblue"
        transform="rotate(10 20,50)">
    SVG Vector Text
  </text>
</svg>
  • transform enables effects like rotation and skew
  • text-anchor controls text alignment (start/middle/end)

Gradients and Filters

Linear Gradient <linearGradient>

<svg width="200" height="200">
  <defs>
    <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
      <stop offset="0%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
      <stop offset="100%" style="stop-color:rgb(0,0,255);stop-opacity:1" />
    </linearGradient>
  </defs>
  <rect x="50" y="50" width="100" height="100" fill="url(#grad1)"/>
</svg>

Gaussian Blur Filter <filter>

<svg width="300" height="150">
  <defs>
    <filter id="blur">
      <feGaussianBlur in="SourceGraphic" stdDeviation="5" />
    </filter>
  </defs>
  <circle cx="100" cy="75" r="50" fill="yellow" filter="url(#blur)"/>
</svg>

Interactivity and Animation

SVG supports dynamic effects via CSS or SMIL:

CSS Hover Effect

<style>
  .svg-rect {
    fill: lightblue;
    transition: fill 0.3s;
  }
  .svg-rect:hover {
    fill: darkblue;
  }
</style>

<svg width="200" height="200">
  <rect class="svg-rect" x="50" y="50" width="100" height="100"/>
</svg>

SMIL Animation

<svg width="300" height="100">
  <rect x="10" y="10" width="50" height="50" fill="green">
    <animate attributeName="x" from="10" to="240" dur="3s" repeatCount="indefinite"/>
  </rect>
</svg>

Responsive SVG

Use the viewBox attribute for responsive scaling:

<svg viewBox="0 0 200 200" style="width: 100%; height: auto;">
  <circle cx="100" cy="100" r="80" fill="gold"/>
</svg>
  • viewBox="min-x min-y width height" defines the coordinate system
  • Percentage width allows the graphic to adapt to its container

JavaScript Interaction

Modify SVG dynamically via the DOM API:

<svg id="demo" width="200" height="200">
  <circle cx="100" cy="100" r="40" fill="gray"/>
</svg>

<script>
  const circle = document.querySelector('#demo circle');
  circle.addEventListener('click', () => {
    circle.setAttribute('fill', getRandomColor());
  });
  
  function getRandomColor() {
    return `hsl(${Math.random() * 360}, 70%, 60%)`;
  }
</script>

Performance Optimization Tips

  1. Reduce node count: Complex paths perform better than multiple simple shapes
  2. Use <symbol>: Define reusable graphics once and reference them via <use>
  3. Compression tools: Use tools like SVGO to remove redundant metadata
  4. Inline vs. external files: Inline small icons; consider external references for large graphics
<svg style="display:none">
  <symbol id="icon-arrow" viewBox="0 0 20 20">
    <path d="M10 0l10 10-10 10L0 10z"/>
  </symbol>
</svg>

<svg class="icon">
  <use xlink:href="#icon-arrow"/>
</svg>

Practical Use Cases

Dynamic Data Visualization

<svg id="chart" width="400" height="300"></svg>

<script>
  const data = [30, 70, 45, 90, 60];
  const chart = document.getElementById('chart');
  
  data.forEach((value, i) => {
    const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
    rect.setAttribute('x', i * 80 + 10);
    rect.setAttribute('y', 300 - value * 2);
    rect.setAttribute('width', 60);
    rect.setAttribute('height', value * 2);
    rect.setAttribute('fill', `hsl(${i * 70}, 80%, 50%)`);
    chart.appendChild(rect);
  });
</script>

Custom Checkbox

<label>
  <input type="checkbox" class="hidden-checkbox">
  <svg class="svg-checkbox" width="24" height="24">
    <rect x="2" y="2" width="20" height="20" rx="3" 
          stroke="#555" stroke-width="2" fill="white"/>
    <path d="M6 12 L10 16 L18 8" 
          stroke="transparent" stroke-width="3" 
          fill="none" class="checkmark"/>
  </svg>
  Custom Checkbox
</label>

<style>
  .hidden-checkbox { display: none; }
  .svg-checkbox .checkmark { transition: stroke 0.2s; }
  .hidden-checkbox:checked + .svg-checkbox .checkmark {
    stroke: green;
  }
</style>

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.