svg

package module
v0.0.0-...-fb2a099 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 10, 2025 License: MIT Imports: 15 Imported by: 0

README

SVG Library for Go

一个功能强大的Go语言SVG图形库,支持图形绘制、动画制作、文本渲染和高级样式设置。

A powerful SVG graphics library for Go, supporting shape drawing, animation creation, text rendering, and advanced styling.

✨ 特性 Features

  • 🎨 丰富的图形绘制 - 支持矩形、圆形、椭圆、直线、折线、多边形、路径等基础图形
  • 🎬 动画支持 - 内置动画构建器,支持旋转、缩放、移动、颜色变化等动画效果
  • 📝 文本渲染 - 完整的文本渲染系统,支持多种字体、样式和对齐方式
  • 🎨 样式系统 - 支持颜色、渐变、描边、填充、透明度等样式设置
  • 🔄 变换支持 - 支持平移、旋转、缩放、倾斜等2D变换
  • 📊 高级API - 提供链式调用的高级API,简化复杂图形的创建
  • 🖼️ 多格式输出 - 支持SVG、PNG、GIF等多种格式输出
  • 🚀 高性能 - 优化的渲染引擎,支持大规模图形处理

📦 安装 Installation

go get github.com/hoonfeng/svg

🚀 快速开始 Quick Start

基础图形绘制
package main

import (
    "image/color"
    "svg"
)

func main() {
    // 创建SVG画布
    canvas := svg.New(400, 300)
    
    // 设置背景
    canvas.Background(color.RGBA{255, 255, 255, 255})
    
    // 绘制红色圆形
    canvas.Circle(200, 150, 50).
        Fill(color.RGBA{255, 0, 0, 255}).
        Stroke(color.RGBA{0, 0, 0, 255}).
        StrokeWidth(2).
        End()
    
    // 绘制蓝色矩形
    canvas.Rect(100, 100, 200, 100).
        Fill(color.RGBA{0, 0, 255, 255}).
        Opacity(0.7).
        End()
    
    // 添加文本
    canvas.Text(200, 50, "Hello SVG!").
        Fill(color.RGBA{0, 0, 0, 255}).
        FontSize(24).
        FontFamily("Arial").
        TextAnchor("middle").
        End()
    
    // 保存为SVG文件
    canvas.Save("example.svg")
    
    // 保存为PNG文件
    canvas.SavePNG("example.png", 400, 300)
}
动画制作
package main

import (
    "image/color"
    "svg/animation"
)

func main() {
    // 创建动画构建器
    builder := animation.NewAnimationBuilder(400, 300, 3.0) // 3秒动画
    
    // 设置背景
    builder.SetBackground(color.RGBA{240, 240, 240, 255})
    
    // 创建旋转的彩色圆形
    for i := 0; i < 60; i++ {
        frame := float64(i) / 60.0
        
        // 添加帧
        builder.AddFrame(frame)
        
        // 旋转角度
        angle := frame * 360
        
        // 绘制旋转的圆形
        builder.Circle(200, 150, 30).
            Fill(animation.HSL(int(angle), 80, 60)).
            Transform(fmt.Sprintf("rotate(%.1f 200 150)", angle)).
            End()
    }
    
    // 生成GIF动画
    builder.SaveGIF("rotating_circle.gif")
}

支持的SVG元素

  • 矩形 (Rect)
  • 圆形 (Circle)
  • 椭圆 (Ellipse)
  • 线段 (Line)
  • 折线 (Polyline)
  • 多边形 (Polygon)
  • 路径 (Path)
  • 文本 (Text)
  • 组 (Group)

路径命令支持

  • 移动 (M, m)
  • 直线 (L, l)
  • 水平线 (H, h)
  • 垂直线 (V, v)
  • 三次贝塞尔曲线 (C, c)
  • 平滑三次贝塞尔曲线 (S, s)
  • 二次贝塞尔曲线 (Q, q)
  • 平滑二次贝塞尔曲线 (T, t)
  • 椭圆弧 (A, a)
  • 闭合路径 (Z, z)

📚 文档 Documentation

🏗️ 项目结构 Project Structure

svg/
├── animation/          # 动画模块
├── api/               # 高级API
├── attributes/        # 属性和样式
├── cmd/               # 命令行工具和示例
├── elements/          # SVG元素定义
├── examples/          # 示例代码
├── font/              # 字体和文本渲染
├── io/                # 输入输出处理
├── output/            # 输出文件目录
├── parser/            # XML解析器
├── path/              # 路径处理
├── renderer/          # 渲染引擎
├── test_animation/    # 动画测试
├── test_renderer/     # 渲染测试
├── transform/         # 变换处理
├── types/             # 类型定义
├── docs/              # 文档文件
└── svg.go             # 主要API

🎯 主要功能 Main Features

图形绘制
  • ✅ 基础图形:矩形、圆形、椭圆、直线、折线、多边形
  • ✅ 复杂路径:贝塞尔曲线、弧线、复合路径
  • ✅ 分组和嵌套:支持元素分组和层次结构
样式系统
  • ✅ 颜色支持:RGB、RGBA、HSL、命名颜色
  • ✅ 填充和描边:实色、渐变、图案填充
  • ✅ 透明度和混合模式
  • ✅ 滤镜效果
文本处理
  • ✅ 多字体支持:系统字体、自定义字体
  • ✅ 文本样式:粗体、斜体、下划线
  • ✅ 文本对齐:左对齐、居中、右对齐
  • ✅ 文本路径:沿路径排列文本
动画功能
  • ✅ 关键帧动画:位置、旋转、缩放、颜色
  • ✅ 缓动函数:线性、贝塞尔、弹性等
  • ✅ 循环和延迟控制
  • ✅ GIF导出
输出格式
  • ✅ SVG:矢量格式,可缩放
  • ✅ PNG:高质量位图
  • ✅ GIF:动画支持
  • ✅ 批量处理

🔧 系统要求 Requirements

  • Go 1.18 或更高版本
  • 支持的操作系统:Windows、macOS、Linux
  • 可选依赖:
    • 字体文件(用于自定义字体)
    • 图像处理库(用于高级滤镜)

🤝 贡献 Contributing

我们欢迎所有形式的贡献!请查看 CONTRIBUTING.md 了解详细信息。

开发环境设置
# 克隆仓库
git clone https://github.com/hoonfeng/svg.git
cd svg

# 安装依赖
go mod tidy

# 运行测试
go test ./...

# 运行示例
go run examples/animation_builder_demo.go

📄 许可证 License

本项目采用 MIT 许可证 - 查看 LICENSE 文件了解详情。

🙏 致谢 Acknowledgments

  • 感谢所有贡献者的努力
  • 特别感谢开源社区的支持
  • 参考了多个优秀的图形库设计

📞 联系我们 Contact


⭐ 如果这个项目对你有帮助,请给我们一个星标!

⭐ If this project helps you, please give us a star!

Documentation

Overview

高级动画构建器 / Advanced Animation Builder 提供简化的API来创建常见的动画效果 / Provides simplified API for creating common animation effects

Package svg provides a comprehensive SVG (Scalable Vector Graphics) library for Go svg包为Go提供了一个全面的SVG(可缩放矢量图形)库

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ImageToJPEGBytes

func ImageToJPEGBytes(img image.Image, quality int) ([]byte, error)

ImageToJPEGBytes 将图像转换为JPEG字节数据 / Convert image to JPEG bytes

func ImageToPNGBytes

func ImageToPNGBytes(img image.Image) ([]byte, error)

ImageToPNGBytes 将图像转换为PNG字节数据 / Convert image to PNG bytes

func SaveImageToJPEG

func SaveImageToJPEG(img image.Image, filename string, quality int) error

SaveImageToJPEG 保存图像为JPEG文件 / Save image as JPEG file

func SaveImageToPNG

func SaveImageToPNG(img image.Image, filename string) error

SaveImageToPNG 保存图像为PNG文件 / Save image as PNG file

Types

type AnimationBuilder

type AnimationBuilder struct {
	// contains filtered or unexported fields
}

AnimationBuilder 动画构建器 / Animation Builder

func NewAnimationBuilder

func NewAnimationBuilder(width, height int) *AnimationBuilder

NewAnimationBuilder 创建新的动画构建器 / Create new animation builder

func (*AnimationBuilder) CreateColorfulParticles

func (ab *AnimationBuilder) CreateColorfulParticles(config AnimationConfig) *AnimationBuilder

CreateColorfulParticles 创建彩色粒子动画 / Create colorful particles animation

func (*AnimationBuilder) CreatePulsingCircles

func (ab *AnimationBuilder) CreatePulsingCircles(config AnimationConfig) *AnimationBuilder

CreatePulsingCircles 创建脉冲圆形动画 / Create pulsing circles animation

func (*AnimationBuilder) CreateRotatingShapes

func (ab *AnimationBuilder) CreateRotatingShapes(config AnimationConfig) *AnimationBuilder

CreateRotatingShapes 创建旋转图形动画 / Create rotating shapes animation

func (*AnimationBuilder) CreateWaveAnimation

func (ab *AnimationBuilder) CreateWaveAnimation(config AnimationConfig) *AnimationBuilder

CreateWaveAnimation 创建波浪动画 / Create wave animation

func (*AnimationBuilder) GetDuration

func (ab *AnimationBuilder) GetDuration() float64

GetDuration 获取动画时长(秒) / Get animation duration (seconds)

func (*AnimationBuilder) GetFrameCount

func (ab *AnimationBuilder) GetFrameCount() int

GetFrameCount 获取帧数 / Get frame count

func (*AnimationBuilder) SaveToGIF

func (ab *AnimationBuilder) SaveToGIF(filename string) error

SaveToGIF 保存为GIF文件 / Save to GIF file

func (*AnimationBuilder) SetFrameCount

func (ab *AnimationBuilder) SetFrameCount(count int) *AnimationBuilder

SetFrameCount 设置帧数 / Set frame count

func (*AnimationBuilder) SetFrameRate

func (ab *AnimationBuilder) SetFrameRate(fps int) *AnimationBuilder

SetFrameRate 设置帧率 / Set frame rate

type AnimationConfig

type AnimationConfig struct {
	Duration   float64    // 动画持续时间(秒) / Animation duration (seconds)
	Easing     EasingFunc // 缓动函数 / Easing function
	Background color.RGBA // 背景颜色 / Background color
	Loop       bool       // 是否循环 / Whether to loop
}

AnimationConfig 动画配置 / Animation configuration

type ChartElement

type ChartElement struct {
	// contains filtered or unexported fields
}

ChartElement 图表元素 / Chart element

func (*ChartElement) End

func (c *ChartElement) End() *SVG

func (*ChartElement) Fill

func (c *ChartElement) Fill(color color.Color) *ChartElement

func (*ChartElement) Stroke

func (c *ChartElement) Stroke(color color.Color) *ChartElement

type CircleElement

type CircleElement struct {
	// contains filtered or unexported fields
}

CircleElement 圆形元素 / Circle element

func (*CircleElement) End

func (c *CircleElement) End() *SVG

func (*CircleElement) Fill

func (c *CircleElement) Fill(color color.Color) *CircleElement

func (*CircleElement) Stroke

func (c *CircleElement) Stroke(color color.Color) *CircleElement

func (*CircleElement) StrokeWidth

func (c *CircleElement) StrokeWidth(width float64) *CircleElement

type EasingFunc

type EasingFunc func(t float64) float64

EasingFunc 缓动函数类型 / Easing function type

var (
	// Linear 线性缓动 / Linear easing
	Linear EasingFunc = func(t float64) float64 {
		return t
	}

	// EaseInOut 缓入缓出 / Ease in-out
	EaseInOut EasingFunc = func(t float64) float64 {
		if t < 0.5 {
			return 2 * t * t
		}
		return -1 + (4-2*t)*t
	}

	// EaseInQuad 二次方缓入 / Quadratic ease in
	EaseInQuad EasingFunc = func(t float64) float64 {
		return t * t
	}

	// EaseOutQuad 二次方缓出 / Quadratic ease out
	EaseOutQuad EasingFunc = func(t float64) float64 {
		return t * (2 - t)
	}

	// EaseInOutQuad 二次方缓入缓出 / Quadratic ease in-out
	EaseInOutQuad EasingFunc = func(t float64) float64 {
		if t < 0.5 {
			return 2 * t * t
		}
		return -1 + (4-2*t)*t
	}

	// EaseInCubic 三次方缓入 / Cubic ease in
	EaseInCubic EasingFunc = func(t float64) float64 {
		return t * t * t
	}

	// EaseOutCubic 三次方缓出 / Cubic ease out
	EaseOutCubic EasingFunc = func(t float64) float64 {
		t--
		return t*t*t + 1
	}

	// Bounce 弹跳效果 / Bounce effect
	Bounce EasingFunc = func(t float64) float64 {
		if t < 1/2.75 {
			return 7.5625 * t * t
		} else if t < 2/2.75 {
			t -= 1.5 / 2.75
			return 7.5625*t*t + 0.75
		} else if t < 2.5/2.75 {
			t -= 2.25 / 2.75
			return 7.5625*t*t + 0.9375
		} else {
			t -= 2.625 / 2.75
			return 7.5625*t*t + 0.984375
		}
	}
)

预定义缓动函数 / Predefined easing functions

type EllipseElement

type EllipseElement struct {
	// contains filtered or unexported fields
}

EllipseElement 椭圆元素 / Ellipse element

func (*EllipseElement) End

func (e *EllipseElement) End() *SVG

func (*EllipseElement) Fill

func (e *EllipseElement) Fill(color color.Color) *EllipseElement

func (*EllipseElement) Stroke

func (e *EllipseElement) Stroke(color color.Color) *EllipseElement

func (*EllipseElement) StrokeWidth

func (e *EllipseElement) StrokeWidth(width float64) *EllipseElement

type GridElement

type GridElement struct {
	// contains filtered or unexported fields
}

GridElement 网格元素 / Grid element

func (*GridElement) End

func (g *GridElement) End() *SVG

func (*GridElement) LineColor

func (g *GridElement) LineColor(color color.Color) *GridElement

func (*GridElement) LineWidth

func (g *GridElement) LineWidth(width float64) *GridElement

type GroupElement

type GroupElement struct {
	// contains filtered or unexported fields
}

GroupElement 组元素 / Group element

func (*GroupElement) End

func (g *GroupElement) End() *SVG

func (*GroupElement) Rotate

func (g *GroupElement) Rotate(angle float64) *GroupElement

func (*GroupElement) Scale

func (g *GroupElement) Scale(sx, sy float64) *GroupElement

func (*GroupElement) Transform

func (g *GroupElement) Transform(transform string) *GroupElement

func (*GroupElement) Translate

func (g *GroupElement) Translate(x, y float64) *GroupElement

type LineElement

type LineElement struct {
	// contains filtered or unexported fields
}

LineElement 直线元素 / Line element

func (*LineElement) End

func (l *LineElement) End() *SVG

func (*LineElement) Stroke

func (l *LineElement) Stroke(color color.Color) *LineElement

func (*LineElement) StrokeWidth

func (l *LineElement) StrokeWidth(width float64) *LineElement

type PathElement

type PathElement struct {
	// contains filtered or unexported fields
}

PathElement 路径元素 / Path element

func (*PathElement) End

func (p *PathElement) End() *SVG

func (*PathElement) Fill

func (p *PathElement) Fill(color color.Color) *PathElement

func (*PathElement) Stroke

func (p *PathElement) Stroke(color color.Color) *PathElement

func (*PathElement) StrokeWidth

func (p *PathElement) StrokeWidth(width float64) *PathElement

type PatternElement

type PatternElement struct {
	// contains filtered or unexported fields
}

PatternElement 图案元素 / Pattern element

func (*PatternElement) Color

func (p *PatternElement) Color(color color.Color) *PatternElement

func (*PatternElement) End

func (p *PatternElement) End() *SVG

func (*PatternElement) Spacing

func (p *PatternElement) Spacing(spacing float64) *PatternElement

type RectElement

type RectElement struct {
	// contains filtered or unexported fields
}

RectElement 矩形元素 / Rectangle element

func (*RectElement) End

func (r *RectElement) End() *SVG

func (*RectElement) Fill

func (r *RectElement) Fill(c color.Color) *RectElement

func (*RectElement) Rx

func (r *RectElement) Rx(rx float64) *RectElement

func (*RectElement) Ry

func (r *RectElement) Ry(ry float64) *RectElement

func (*RectElement) Stroke

func (r *RectElement) Stroke(c color.Color) *RectElement

func (*RectElement) StrokeWidth

func (r *RectElement) StrokeWidth(width float64) *RectElement

type SVG

type SVG struct {
	// contains filtered or unexported fields
}

SVG 统一的SVG操作接口 / Unified SVG operation interface

func Load

func Load(filename string) (*SVG, error)

Load 从文件加载SVG / Load SVG from file

func New

func New(width, height int) *SVG

New 创建新的SVG实例 / Create new SVG instance

func NewWithViewBox

func NewWithViewBox(width, height int, viewX, viewY, viewWidth, viewHeight float64) *SVG

NewWithViewBox 创建带视图框的SVG实例 / Create SVG instance with viewBox

func Parse

func Parse(svgContent string) (*SVG, error)

Parse 从字符串解析SVG / Parse SVG from string

func (*SVG) Background

func (s *SVG) Background(bgColor color.Color) *SVG

Background 设置背景颜色 / Set background color

func (*SVG) BarChart

func (s *SVG) BarChart(data []float64, x, y, width, height float64) *ChartElement

BarChart 创建柱状图 / Create bar chart

func (*SVG) Circle

func (s *SVG) Circle(cx, cy, r float64) *CircleElement

Circle 创建圆形 / Create circle

func (*SVG) DotPattern

func (s *SVG) DotPattern(spacing, radius float64) *PatternElement

DotPattern 创建点图案 / Create dot pattern

func (*SVG) Ellipse

func (s *SVG) Ellipse(cx, cy, rx, ry float64) *EllipseElement

Ellipse 创建椭圆 / Create ellipse

func (*SVG) GetDocument

func (s *SVG) GetDocument() *Document

GetDocument 获取文档 / Get document

func (*SVG) GetImageData

func (s *SVG) GetImageData(width, height int) (*image.RGBA, error)

GetImageData 获取图像数据 / Get image data

func (*SVG) GetJPEGData

func (s *SVG) GetJPEGData(width, height int, quality int) ([]byte, error)

GetJPEGData 获取JPEG格式的图像数据 / Get JPEG format image data

func (*SVG) GetPNGData

func (s *SVG) GetPNGData(width, height int) ([]byte, error)

GetPNGData 获取PNG格式的图像数据 / Get PNG format image data

func (*SVG) GetSize

func (s *SVG) GetSize() (int, int)

GetSize 获取画布尺寸 / Get canvas size

func (*SVG) Grid

func (s *SVG) Grid(rows, cols int, cellWidth, cellHeight float64) *GridElement

Grid 创建网格 / Create grid

func (*SVG) Group

func (s *SVG) Group() *GroupElement

Group 开始组 / Begin group

func (*SVG) Heart

func (s *SVG) Heart(cx, cy, size float64) *ShapeElement

Heart 创建心形 / Create heart

func (*SVG) Line

func (s *SVG) Line(x1, y1, x2, y2 float64) *LineElement

Line 创建直线 / Create line

func (*SVG) LineChart

func (s *SVG) LineChart(data []float64, x, y, width, height float64) *ChartElement

LineChart 创建折线图 / Create line chart

func (*SVG) Path

func (s *SVG) Path(d string) *PathElement

Path 创建路径 / Create path

func (*SVG) PieChart

func (s *SVG) PieChart(data []float64, cx, cy, radius float64) *ChartElement

PieChart 创建饼图 / Create pie chart

func (*SVG) Polygon

func (s *SVG) Polygon(cx, cy, radius float64, sides int) *ShapeElement

Polygon 创建多边形 / Create polygon

func (*SVG) Rect

func (s *SVG) Rect(x, y, width, height float64) *RectElement

Rect 创建矩形 / Create rectangle

func (*SVG) Render

func (s *SVG) Render(width, height int) (*image.RGBA, error)

Render 渲染为图像 / Render to image

func (*SVG) RenderToSize

func (s *SVG) RenderToSize(width, height int) (*image.RGBA, error)

RenderToSize 渲染到指定尺寸 / Render to specified size

func (*SVG) Save

func (s *SVG) Save(filename string) error

Save 保存为SVG文件 / Save as SVG file

func (*SVG) SaveImage

func (s *SVG) SaveImage(filename string, width, height int, format string, quality ...int) error

SaveImage 保存为指定格式的图片文件 / Save as image file in specified format

func (*SVG) SaveJPEG

func (s *SVG) SaveJPEG(filename string, width, height int, quality int) error

SaveJPEG 保存为JPEG文件 / Save as JPEG file

func (*SVG) SavePNG

func (s *SVG) SavePNG(filename string, width, height int) error

SavePNG 保存为PNG文件 / Save as PNG file

func (*SVG) SetSize

func (s *SVG) SetSize(width, height int) *SVG

SetSize 设置画布尺寸 / Set canvas size

func (*SVG) Star

func (s *SVG) Star(cx, cy, outerRadius float64, points int) *ShapeElement

Star 创建星形 / Create star

func (*SVG) String

func (s *SVG) String() string

String 转换为SVG字符串 / Convert to SVG string

func (*SVG) Text

func (s *SVG) Text(x, y float64, text string) *TextElement

Text 创建文本 / Create text

type ShapeElement

type ShapeElement struct {
	// contains filtered or unexported fields
}

ShapeElement 形状元素 / Shape element

func (*ShapeElement) End

func (s *ShapeElement) End() *SVG

func (*ShapeElement) Fill

func (s *ShapeElement) Fill(color color.Color) *ShapeElement

func (*ShapeElement) Stroke

func (s *ShapeElement) Stroke(color color.Color) *ShapeElement

func (*ShapeElement) StrokeWidth

func (s *ShapeElement) StrokeWidth(width float64) *ShapeElement

type TextElement

type TextElement struct {
	// contains filtered or unexported fields
}

TextElement 文本元素 / Text element

func (*TextElement) End

func (t *TextElement) End() *SVG

func (*TextElement) Fill

func (t *TextElement) Fill(color color.Color) *TextElement

func (*TextElement) FontFamily

func (t *TextElement) FontFamily(family string) *TextElement

func (*TextElement) FontSize

func (t *TextElement) FontSize(size float64) *TextElement

func (*TextElement) FontWeight

func (t *TextElement) FontWeight(weight string) *TextElement

Directories

Path Synopsis
Package api provides high-level APIs for SVG creation and manipulation api包为SVG创建和操作提供高级API
Package api provides high-level APIs for SVG creation and manipulation api包为SVG创建和操作提供高级API
cmd
example command
高级动画构建器演示程序 / Advanced Animation Builder Demo
高级动画构建器演示程序 / Advanced Animation Builder Demo
example command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL