### Complete Go SVG Basic Shapes Example
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICK_START.md
A comprehensive example demonstrating the creation of an SVG canvas, setting a background, drawing multiple rectangles, circles, and lines with various colors, and adding a title. The final output is saved as both SVG and PNG files, showcasing a complete basic drawing scenario.
```Go
package main
import (
"image/color"
"svg"
)
func main() {
// 创建画布 / Create canvas
canvas := svg.New(400, 400)
canvas.SetBackground(color.RGBA{250, 250, 250, 255})
// 绘制彩色矩形 / Draw colorful rectangles
canvas.Rect(50, 50, 80, 60).Fill(color.RGBA{255, 100, 100, 255})
canvas.Rect(150, 50, 80, 60).Fill(color.RGBA{100, 255, 100, 255})
canvas.Rect(250, 50, 80, 60).Fill(color.RGBA{100, 100, 255, 255})
// 绘制圆形 / Draw circles
canvas.Circle(90, 180, 30).Fill(color.RGBA{255, 200, 0, 255})
canvas.Circle(190, 180, 30).Fill(color.RGBA{255, 0, 200, 255})
canvas.Circle(290, 180, 30).Fill(color.RGBA{0, 255, 200, 255})
// 绘制线条 / Draw lines
canvas.Line(50, 250, 350, 250).Stroke(color.RGBA{100, 100, 100, 255}).StrokeWidth(3)
canvas.Line(200, 280, 200, 350).Stroke(color.RGBA{100, 100, 100, 255}).StrokeWidth(3)
// 添加标题 / Add title
canvas.Text(200, 30, "基本图形示例").FontSize(20).TextAnchor("middle").Fill(color.RGBA{50, 50, 50, 255})
// 保存文件 / Save files
canvas.SaveSVG("basic_shapes.svg")
canvas.SavePNG("basic_shapes.png")
}
```
--------------------------------
### Install Go SVG Library
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICKSTART.md
This command installs the `github.com/hoonfeng/svg` library into your Go module. It fetches the library and its dependencies, making it available for use in your Go project.
```bash
go get github.com/hoonfeng/svg
```
--------------------------------
### Verify Go SVG Library Installation
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICKSTART.md
This Go program imports the `github.com/hoonfeng/svg` library and prints a confirmation message. It serves as a basic test to ensure the library was successfully installed and can be imported without errors.
```go
package main
import (
"fmt"
"github.com/hoonfeng/svg"
)
func main() {
fmt.Println("SVG库安装成功!")
fmt.Println("SVG library installed successfully!")
}
```
--------------------------------
### Run Go Example Application
Source: https://github.com/hoonfeng/svg/blob/main/CONTRIBUTING.md
Command to compile and run a specific Go example file, demonstrating project functionality.
```bash
go run examples/animation_builder_demo.go
```
--------------------------------
### Run Go Program to Verify SVG Library
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICKSTART.md
This command executes the `main.go` file, which contains the verification code for the SVG library. Running this command will output the confirmation message if the library is correctly installed.
```bash
go run main.go
```
--------------------------------
### Initialize Go Module for SVG Project
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICKSTART.md
This snippet demonstrates how to set up a new Go module for a project. It creates a new directory, navigates into it, and initializes a Go module, preparing the environment for Go development.
```bash
mkdir my-svg-project
cd my-svg-project
go mod init my-svg-project
```
--------------------------------
### Install Go Project Dependencies
Source: https://github.com/hoonfeng/svg/blob/main/CONTRIBUTING.md
Command to synchronize and download all necessary Go module dependencies for the project.
```bash
go mod tidy
```
--------------------------------
### Go Table-Driven Test Example
Source: https://github.com/hoonfeng/svg/blob/main/CONTRIBUTING.md
Example Go test function demonstrating a table-driven testing pattern for the `Circle` function, including test cases and structure.
```go
func TestCircle(t *testing.T) {
tests := []struct {
name string
x, y, r float64
want string
}{
{"basic circle", 10, 20, 5, ``},
// 更多测试用例...
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// 测试实现...
})
}
}
```
--------------------------------
### Optimize SVG Performance with Batch Element Addition in Go
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICKSTART.md
This Go example shows a strategy for improving performance when dealing with a large number of SVG elements. By creating a slice of `svg.Element` and adding them in a batch using `svg.AddElements`, it significantly reduces overhead compared to adding elements individually in a loop.
```Go
// 批量添加元素
// Batch add elements
elements := make([]svg.Element, 0, 1000)
for i := 0; i < 1000; i++ {
circle := svg.Circle(float64(i%100*8), float64(i/100*8), 2)
elements = append(elements, circle)
}
svg.AddElements(elements...)
```
--------------------------------
### Verify Go Installation
Source: https://github.com/hoonfeng/svg/blob/main/CONTRIBUTING.md
Command to check the installed Go version, ensuring it meets the project's minimum requirement of Go 1.18 or higher.
```bash
go version
```
--------------------------------
### Execute Go Program to Generate SVG
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICKSTART.md
This command runs the Go program that generates the SVG and PNG files. After execution, `my_first_svg.svg` and `my_first_svg.png` will be created in the current directory.
```bash
go run main.go
```
--------------------------------
### Create a Simple Rotating GIF Animation in Go
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICK_START.md
Illustrates how to generate a basic GIF animation with rotating shapes using the SVG library's animation builder. It covers setting up animation parameters like frame count, frame rate, duration, easing, and background color. The example shows how to configure and save the animation to a GIF file, including error handling.
```Go
package main
import (
"image/color"
"svg"
)
func main() {
// 使用动画构建器 / Use animation builder
builder := svg.NewAnimationBuilder(400, 400)
builder.SetFrameCount(60).SetFrameRate(30)
// 配置动画 / Configure animation
config := svg.AnimationConfig{
Duration: 2.0, // 2秒 / 2 seconds
Easing: svg.EaseInOut,
Background: color.RGBA{20, 20, 40, 255},
Loop: true,
}
// 创建旋转图形动画 / Create rotating shapes animation
err := builder.CreateRotatingShapes(config).SaveToGIF("rotation.gif")
if err != nil {
fmt.Printf("创建动画失败: %v\n", err)
return
}
fmt.Println("✅ 动画已创建: rotation.gif")
}
```
--------------------------------
### Manage File Paths and Directories in Go
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICK_START.md
Illustrates how to create output directories and save SVG and PNG files to specified paths. It uses `os.MkdirAll` to ensure the target directory exists before saving, which is crucial for organizing generated files and preventing file-saving errors.
```Go
// 创建输出目录 / Create output directory
os.MkdirAll("output", 0755)
// 保存到指定目录 / Save to specific directory
canvas.SaveSVG("output/my_drawing.svg")
canvas.SavePNG("output/my_drawing.png")
```
--------------------------------
### Create and Save Basic SVG and PNG with Go SVG
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICK_START.md
Demonstrates creating an SVG canvas, setting a background color, drawing a red circle, adding text, and saving the output as both SVG and PNG files. Includes error handling for file operations and instructions to run the Go program.
```Go
package main
import (
"fmt"
"image/color"
"svg"
)
func main() {
// 创建SVG画布 / Create SVG canvas
canvas := svg.New(400, 300)
// 设置背景颜色 / Set background color
canvas.SetBackground(color.RGBA{240, 248, 255, 255}) // 淡蓝色 / Light blue
// 添加一个红色圆形 / Add a red circle
canvas.Circle(200, 150, 50).Fill(color.RGBA{255, 0, 0, 255})
// 添加文本 / Add text
canvas.Text(200, 200, "Hello SVG!").FontSize(24).TextAnchor("middle")
// 保存为SVG文件 / Save as SVG file
err := canvas.SaveSVG("hello.svg")
if err != nil {
fmt.Printf("保存失败: %v\n", err)
return
}
// 保存为PNG图片 / Save as PNG image
err = canvas.SavePNG("hello.png")
if err != nil {
fmt.Printf("保存PNG失败: %v\n", err)
return
}
fmt.Println("✅ SVG文件已创建: hello.svg")
fmt.Println("✅ PNG文件已创建: hello.png")
}
```
```Bash
go run main.go
```
--------------------------------
### Apply Stroke Settings to Shapes in Go SVG
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICK_START.md
Illustrates how to set the stroke color and width for shapes in Go SVG. This example demonstrates applying a white fill, a black stroke, and a specific stroke width to a circle, controlling its border appearance.
```Go
// 设置描边颜色和宽度 / Set stroke color and width
canvas.Circle(150, 150, 40).
Fill(color.RGBA{255, 255, 255, 255}). // 白色填充 / White fill
Stroke(color.RGBA{0, 0, 0, 255}). // 黑色描边 / Black stroke
StrokeWidth(3) // 描边宽度3 / Stroke width 3
```
--------------------------------
### Set Up Go SVG Library Development Environment
Source: https://github.com/hoonfeng/svg/blob/main/README.md
This snippet provides commands to set up the development environment for the `hoonfeng/svg` library. It covers cloning the repository, installing dependencies, running tests, and executing example programs.
```bash
# 克隆仓库
git clone https://github.com/hoonfeng/svg.git
cd svg
# 安装依赖
go mod tidy
# 运行测试
go test ./...
# 运行示例
go run examples/animation_builder_demo.go
```
--------------------------------
### Draw Lines with Go SVG
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICK_START.md
Demonstrates drawing a straight line on the SVG canvas using the Go SVG library. This snippet illustrates how to specify the line's start and end points, stroke color, and stroke width.
```Go
// 直线 / Line
canvas.Line(50, 300, 350, 300).Stroke(color.RGBA{0, 0, 0, 255}).StrokeWidth(2)
```
--------------------------------
### Illustrate Good Code Documentation Practices in Go
Source: https://github.com/hoonfeng/svg/blob/main/docs/BEST_PRACTICES.md
Demonstrates best practices for documenting Go code, including struct and function comments, parameter descriptions, return values, error handling, and usage examples. It showcases a `ChartRenderer` with detailed explanations for its capabilities and initialization.
```go
// 良好的文档示例
// Good documentation example
// ChartRenderer 提供图表渲染功能
// ChartRenderer provides chart rendering capabilities
//
// 支持的图表类型:
// Supported chart types:
// - 柱状图 (Bar charts)
// - 折线图 (Line charts)
// - 饼图 (Pie charts)
// - 散点图 (Scatter plots)
//
// 使用示例:
// Usage example:
// renderer := NewChartRenderer(800, 600)
// chart := renderer.CreateBarChart(data).
// SetTitle("Sales Data").
// SetColors([]string{"#FF6B6B", "#4ECDC4"}).
// Build()
// chart.SaveSVG("chart.svg")
type ChartRenderer struct {
width int
height int
config ChartConfig
}
// NewChartRenderer 创建新的图表渲染器
// NewChartRenderer creates a new chart renderer
//
// 参数:
// Parameters:
// width: 图表宽度,必须大于0 / Chart width, must be greater than 0
// height: 图表高度,必须大于0 / Chart height, must be greater than 0
//
// 返回值:
// Returns:
// *ChartRenderer: 图表渲染器实例 / Chart renderer instance
//
// 错误:
// Errors:
// 如果width或height小于等于0,将panic
// Panics if width or height is less than or equal to 0
func NewChartRenderer(width, height int) *ChartRenderer {
if width <= 0 || height <= 0 {
panic("width and height must be positive")
}
return &ChartRenderer{
width: width,
height: height,
config: DefaultChartConfig,
}
}
```
--------------------------------
### Import Go SVG Library Packages
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICK_START.md
Imports the necessary `image/color` and `svg` packages for Go SVG graphic manipulation. These packages provide functionalities for defining colors and interacting with the SVG drawing canvas.
```Go
package main
import (
"image/color"
"svg"
)
```
--------------------------------
### Apply Method Chaining for SVG Elements in Go
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICK_START.md
Shows how to use method chaining to configure SVG elements concisely. This pattern allows multiple methods to be called sequentially on the same object, improving code readability and reducing verbosity when setting properties like fill color, stroke color, and stroke width for a shape.
```Go
// 可以链式调用方法 / You can chain methods
canvas.Circle(200, 200, 50).
Fill(color.RGBA{255, 0, 0, 255}).
Stroke(color.RGBA{0, 0, 0, 255}).
StrokeWidth(2)
```
--------------------------------
### Debug SVG Rendering Issues in Go
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICK_START.md
Provides a practical debugging strategy for SVG rendering problems. It suggests saving the output first as an SVG file to inspect its structure and then as a PNG to visualize the rendered result, helping to pinpoint discrepancies between the SVG definition and its rasterized output.
```Go
// 先保存为SVG查看结构 / Save as SVG first to check structure
canvas.SaveSVG("debug.svg")
// 然后保存为PNG查看渲染结果 / Then save as PNG to see rendering result
canvas.SavePNG("debug.png")
```
--------------------------------
### Go SVG Circle Element Function Example
Source: https://github.com/hoonfeng/svg/blob/main/CONTRIBUTING.md
Example Go function demonstrating how to define a public method for creating a circle element in the SVG library, including bilingual comments for parameters.
```go
// Circle 创建一个圆形元素 / Creates a circle element
// x, y: 圆心坐标 / Center coordinates
// r: 半径 / Radius
func (s *SVG) Circle(x, y, r float64) *CircleElement {
// 实现代码...
}
```
--------------------------------
### Apply Text Styles in Go SVG
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICK_START.md
Shows how to apply various styles to text elements in Go SVG. This includes setting font size, font weight (e.g., bold), text alignment using `TextAnchor`, and fill color, allowing for flexible text presentation.
```Go
// 基本文本 / Basic text
canvas.Text(200, 100, "普通文本").FontSize(16)
// 粗体文本 / Bold text
canvas.Text(200, 130, "粗体文本").FontSize(16).FontWeight("bold")
// 居中文本 / Centered text
canvas.Text(200, 160, "居中文本").FontSize(16).TextAnchor("middle")
// 彩色文本 / Colored text
canvas.Text(200, 190, "彩色文本").FontSize(16).Fill(color.RGBA{255, 0, 0, 255})
```
--------------------------------
### Generate SVG and PNG Graphics with Go SVG Library
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICKSTART.md
This comprehensive Go example demonstrates how to create a complex SVG graphic using the `github.com/hoonfeng/svg` library. It initializes an SVG canvas, adds various shapes (rectangles, circles, ellipses), text elements with styling, and a decorative line. Finally, it saves the generated graphic as both an SVG file and renders it to a PNG image, showcasing the library's capabilities for vector and raster output.
```go
package main
import (
"log"
"github.com/hoonfeng/svg"
)
func main() {
// 创建800x600的SVG画布
// Create an 800x600 SVG canvas
s := svg.New(800, 600)
// 添加背景矩形
// Add background rectangle
background := s.Rect(0, 0, 800, 600)
background.Fill("#f0f8ff") // 淡蓝色背景 / Light blue background
// 添加标题文本
// Add title text
title := s.Text(400, 50, "我的第一个SVG / My First SVG")
title.FontFamily("Arial")
.FontSize(32)
.FontWeight("bold")
.Fill("#333333")
.TextAnchor("middle") // 居中对齐 / Center align
// 添加红色圆形
// Add red circle
circle := s.Circle(200, 200, 80)
circle.Fill("#ff6b6b")
.Stroke("#d63031", 3)
.Opacity(0.8)
// 添加蓝色矩形
// Add blue rectangle
rect := s.Rect(350, 120, 160, 160)
rect.Fill("#74b9ff")
.Stroke("#0984e3", 3)
.Rx(20) // 圆角 / Rounded corners
.Ry(20)
// 添加绿色椭圆
// Add green ellipse
ellipse := s.Ellipse(600, 200, 100, 60)
ellipse.Fill("#55a3ff")
.Stroke("#00b894", 3)
// 添加描述文本
// Add description text
desc := s.Text(400, 350, "圆形、矩形和椭圆 / Circle, Rectangle and Ellipse")
desc.FontFamily("Arial")
.FontSize(18)
.Fill("#666666")
.TextAnchor("middle")
// 添加一条装饰线
// Add a decorative line
line := s.Line(100, 400, 700, 400)
line.Stroke("#ddd", 2)
.StrokeDashArray("10,5")
// 保存SVG文件
// Save SVG file
if err := s.Save("my_first_svg.svg"); err != nil {
log.Fatal("保存SVG失败:", err)
}
// 渲染为PNG图像
// Render to PNG image
if err := s.RenderToPNG("my_first_svg.png", 800, 600); err != nil {
log.Fatal("渲染PNG失败:", err)
}
fmt.Println("✅ SVG和PNG文件创建成功!")
fmt.Println("✅ SVG and PNG files created successfully!")
}
```
--------------------------------
### Set Canvas Dimensions in Go
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICK_START.md
Explains how to initialize a new SVG canvas with specific width and height dimensions using `svg.New()`. This is the fundamental step for defining the drawing area for all subsequent SVG elements.
```Go
// 创建指定大小的画布 / Create canvas with specified size
canvas := svg.New(800, 600) // 宽800,高600 / Width 800, Height 600
```
--------------------------------
### Draw Rectangles with Go SVG
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICK_START.md
Illustrates how to draw basic rectangles and rectangles with rounded corners using the Go SVG library. This snippet demonstrates applying different fill colors and setting the corner radius (`Rx`) for a rectangle.
```Go
// 创建矩形 / Create rectangle
canvas.Rect(50, 50, 100, 80).Fill(color.RGBA{0, 255, 0, 255})
// 带圆角的矩形 / Rectangle with rounded corners
canvas.Rect(200, 50, 100, 80).Fill(color.RGBA{0, 0, 255, 255}).Rx(10)
```
--------------------------------
### Profile SVG Generation Performance in Go
Source: https://github.com/hoonfeng/svg/blob/main/docs/TROUBLESHOOTING.md
Provides a `ProfileSVGGeneration` function that demonstrates how to enable CPU and memory profiling using Go's `pprof` package for an SVG generation process. It includes an example of generating a large number of rectangles.
```Go
// 性能分析工具
// Performance profiling tools
func ProfileSVGGeneration() {
// 启用CPU分析
// Enable CPU profiling
cpuFile, err := os.Create("cpu.prof")
if err != nil {
log.Fatal(err)
}
defer cpuFile.Close()
pprof.StartCPUProfile(cpuFile)
defer pprof.StopCPUProfile()
// 启用内存分析
// Enable memory profiling
defer func() {
memFile, err := os.Create("mem.prof")
if err != nil {
log.Fatal(err)
}
defer memFile.Close()
runtime.GC()
pprof.WriteHeapProfile(memFile)
}()
// 执行性能测试
// Execute performance test
canvas := svg.New(1000, 1000)
for i := 0; i < 10000; i++ {
canvas.Rect(float64(i%1000), float64(i/1000), 1, 1).
Fill(fmt.Sprintf("hsl(%d, 50%%, 50%%)", i%360))
}
canvas.SaveSVG("performance_test.svg")
}
```
--------------------------------
### Implement Robust Error Handling in Go
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICK_START.md
Highlights the importance of checking for errors after operations that might fail, such as saving files. This standard Go practice ensures that potential issues are caught and handled gracefully, preventing unexpected program termination and providing informative feedback to the user.
```Go
// 总是检查错误 / Always check errors
if err := canvas.SaveSVG("output.svg"); err != nil {
fmt.Printf("保存失败: %v\n", err)
return
}
```
--------------------------------
### Render Text and Apply Font Styles in Go SVG
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICKSTART.md
This Go code illustrates how to render text elements in SVG using the `hoonfeng/svg` library. It demonstrates setting various font properties such as family, size, weight, and style, as well as applying different colors to text. The output includes both an SVG file and a PNG image.
```go
package main
import (
"log"
"github.com/hoonfeng/svg"
)
func main() {
s := svg.New(800, 600)
// 背景
// Background
bg := s.Rect(0, 0, 800, 600)
bg.Fill("#f8f9fa")
// 标题
// Title
title := s.Text(400, 60, "字体样式演示 / Font Style Demo")
title.FontFamily("Arial")
.FontSize(36)
.FontWeight("bold")
.Fill("#2d3436")
.TextAnchor("middle")
// 不同字体族示例
// Different font family examples
fonts := []struct {
family string
text string
y float64
}{
{"Arial", "Arial字体 - 现代无衬线字体 / Arial Font - Modern Sans-serif", 120},
{"Times New Roman", "Times字体 - 经典衬线字体 / Times Font - Classic Serif", 160},
{"Courier New", "Courier字体 - 等宽字体 / Courier Font - Monospace", 200},
{"Microsoft YaHei", "微软雅黑 - 中文字体 / Microsoft YaHei - Chinese Font", 240},
}
for _, font := range fonts {
text := s.Text(50, font.y, font.text)
text.FontFamily(font.family)
.FontSize(20)
.Fill("#636e72")
}
// 字体样式示例
// Font style examples
styles := []struct {
weight string
style string
text string
y float64
}{
{"normal", "normal", "正常样式 / Normal Style", 320},
{"bold", "normal", "粗体样式 / Bold Style", 360},
{"normal", "italic", "斜体样式 / Italic Style", 400},
{"bold", "italic", "粗斜体样式 / Bold Italic Style", 440},
}
for _, style := range styles {
text := s.Text(50, style.y, style.text)
text.FontFamily("Arial")
.FontSize(24)
.FontWeight(style.weight)
.FontStyle(style.style)
.Fill("#2d3436")
}
// 彩色文本示例
// Colorful text examples
colors := []string{"#e17055", "#74b9ff", "#55a3ff", "#fd79a8", "#fdcb6e"}
for i, color := range colors {
text := s.Text(50+float64(i*140), 520, fmt.Sprintf("彩色%d", i+1))
text.FontFamily("Arial")
.FontSize(28)
.FontWeight("bold")
.Fill(color)
}
// 保存文件
// Save files
if err := s.Save("font_demo.svg"); err != nil {
log.Fatal(err)
}
if err := s.RenderToPNG("font_demo.png", 800, 600); err != nil {
log.Fatal(err)
}
fmt.Println("📝 字体演示文件创建成功!")
fmt.Println("📝 Font demo files created successfully!")
}
```
--------------------------------
### Showcase Text Styles and Typography in SVG with Go
Source: https://github.com/hoonfeng/svg/blob/main/docs/EXAMPLES.md
This Go code snippet illustrates how to apply various text styles and typography effects within an SVG image. It covers setting font size, font weight, text color, text alignment (start, middle, end), and text decorations (underline, overline, line-through) using the 'svg' package to generate the output.
```go
package main
import (
"image/color"
"svg"
)
func main() {
canvas := svg.New(800, 600)
canvas.SetBackground(color.RGBA{255, 255, 255, 255})
// 标题 / Title
canvas.Text(400, 50, "文本样式展示").
FontSize(32).
FontWeight("bold").
TextAnchor("middle").
Fill(color.RGBA{0, 0, 0, 255})
// 不同大小的文本 / Different text sizes
sizes := []float64{12, 16, 20, 24, 28, 32}
for i, size := range sizes {
canvas.Text(50, float64(100+i*40), fmt.Sprintf("字体大小 %.0fpx", size)).
FontSize(size).
Fill(color.RGBA{0, 0, 0, 255})
}
// 不同字体粗细 / Different font weights
weights := []string{"100", "300", "400", "600", "700", "900"}
for i, weight := range weights {
canvas.Text(300, float64(100+i*40), fmt.Sprintf("粗细 %s", weight)).
FontSize(18).
FontWeight(weight).
Fill(color.RGBA{0, 0, 0, 255})
}
// 彩色文本 / Colored text
colors := []color.RGBA{
{255, 0, 0, 255},
{0, 255, 0, 255},
{0, 0, 255, 255},
{255, 165, 0, 255},
{128, 0, 128, 255},
{255, 20, 147, 255},
}
for i, c := range colors {
canvas.Text(500, float64(100+i*40), "彩色文本").
FontSize(18).
Fill(c)
}
// 文本对齐 / Text alignment
alignments := []string{"start", "middle", "end"}
for i, align := range alignments {
y := float64(400 + i*30)
// 绘制参考线 / Draw reference line
canvas.Line(400, y, 400, y).
Stroke(color.RGBA{200, 200, 200, 255}).
StrokeWidth(1)
canvas.Text(400, y, fmt.Sprintf("对齐方式: %s", align)).
FontSize(16).
TextAnchor(align).
Fill(color.RGBA{0, 0, 0, 255})
}
// 文本装饰 / Text decorations
decorations := []string{"underline", "overline", "line-through"}
for i, decoration := range decorations {
canvas.Text(50, float64(500+i*30), fmt.Sprintf("装饰: %s", decoration)).
FontSize(16).
TextDecoration(decoration).
Fill(color.RGBA{0, 0, 0, 255})
}
canvas.SaveSVG("text_styles.svg")
canvas.SavePNG("text_styles.png")
}
```
--------------------------------
### Generate Complex SVG Paths and Curves with Go
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICKSTART.md
This Go program uses the `hoonfeng/svg` library to create an SVG file (`paths_demo.svg`) and a PNG image (`paths_demo.png`) demonstrating various path and curve types. It includes examples for simple triangles, Bézier curves, complex heart shapes, sine waves, and spirals, along with text annotations and basic styling.
```Go
package main
import (
"log"
"math"
"github.com/hoonfeng/svg"
)
func main() {
s := svg.New(800, 600)
// 背景
bg := s.Rect(0, 0, 800, 600)
bg.Fill("#2d3436")
// 标题
title := s.Text(400, 40, "路径和曲线演示 / Paths and Curves Demo")
title.FontFamily("Arial")
.FontSize(28)
.FontWeight("bold")
.Fill("white")
.TextAnchor("middle")
// 1. 简单路径 - 三角形
// Simple path - triangle
trianglePath := "M 100 100 L 200 100 L 150 50 Z"
triangle := s.Path(trianglePath)
triangle.Fill("#74b9ff")
.Stroke("#0984e3", 2)
// 2. 贝塞尔曲线
// Bézier curves
curvePath := "M 300 100 Q 400 50 500 100 T 700 100"
curve := s.Path(curvePath)
curve.Fill("none")
.Stroke("#55a3ff", 3)
// 3. 复杂路径 - 心形
// Complex path - heart shape
heartPath := "M 400 200 C 400 180, 380 160, 360 160 C 340 160, 320 180, 320 200 C 320 220, 400 280, 400 280 C 400 280, 480 220, 480 200 C 480 180, 460 160, 440 160 C 420 160, 400 180, 400 200 Z"
heart := s.Path(heartPath)
heart.Fill("#fd79a8")
.Stroke("#e84393", 2)
// 4. 使用路径构建器创建波浪线
// Create wave using path builder
builder := svg.NewPathBuilder()
builder.MoveTo(50, 350)
// 创建正弦波
// Create sine wave
for x := 0; x <= 700; x += 10 {
y := 350 + 50*math.Sin(float64(x)*math.Pi/100)
builder.LineTo(float64(50+x), y)
}
wave := s.Path(builder.String())
wave.Fill("none")
.Stroke("#00b894", 3)
.StrokeDashArray("5,5")
// 5. 螺旋线
// Spiral
spiralBuilder := svg.NewPathBuilder()
centerX, centerY := 400.0, 450.0
spiralBuilder.MoveTo(centerX, centerY)
for i := 0; i < 360*3; i += 5 {
angle := float64(i) * math.Pi / 180
radius := float64(i) / 10
x := centerX + radius*math.Cos(angle)
y := centerY + radius*math.Sin(angle)
spiralBuilder.LineTo(x, y)
}
spiral := s.Path(spiralBuilder.String())
spiral.Fill("none")
.Stroke("#fdcb6e", 2)
// 添加说明文本
// Add description text
descriptions := []struct {
text string
x, y float64
}{
{"三角形 / Triangle", 150, 130},
{"贝塞尔曲线 / Bézier Curve", 500, 130},
{"心形 / Heart", 400, 320},
{"正弦波 / Sine Wave", 400, 380},
{"螺旋线 / Spiral", 400, 550}
}
for _, desc := range descriptions {
text := s.Text(desc.x, desc.y, desc.text)
text.FontFamily("Arial")
.FontSize(14)
.Fill("#ddd")
.TextAnchor("middle")
}
// 保存文件
if err := s.Save("paths_demo.svg"); err != nil {
log.Fatal(err)
}
if err := s.RenderToPNG("paths_demo.png", 800, 600); err != nil {
log.Fatal(err)
}
fmt.Println("🎨 路径演示文件创建成功!")
fmt.Println("🎨 Paths demo files created successfully!")
}
```
--------------------------------
### Create a Basic SVG with Text in Go
Source: https://github.com/hoonfeng/svg/blob/main/docs/EXAMPLES.md
This example demonstrates the simplest SVG program using the Go SVG library. It initializes a canvas, sets a background color, adds 'Hello, SVG!' text centered on the canvas, and then saves the output as both SVG and PNG files.
```Go
package main
import (
"image/color"
"svg"
)
func main() {
// 创建画布 / Create canvas
canvas := svg.New(300, 200)
// 设置背景 / Set background
canvas.SetBackground(color.RGBA{240, 248, 255, 255})
// 添加文本 / Add text
canvas.Text(150, 100, "Hello, SVG!").
FontSize(24).
TextAnchor("middle").
Fill(color.RGBA{0, 0, 0, 255})
// 保存文件 / Save file
canvas.SaveSVG("hello_world.svg")
canvas.SavePNG("hello_world.png")
}
```
--------------------------------
### Orchestrate Chart Generation in Go
Source: https://github.com/hoonfeng/svg/blob/main/docs/EXAMPLES.md
This Go `main` function demonstrates how to call various chart creation functions (e.g., bar, pie, line) and prints a confirmation message upon completion. It serves as an entry point for generating multiple types of charts sequentially.
```Go
func main() {
createBarChart()
createPieChart()
createLineChart()
fmt.Println("✅ 所有图表已创建完成")
}
```
--------------------------------
### Main Function for QR Code Pattern Generation in Go
Source: https://github.com/hoonfeng/svg/blob/main/docs/EXAMPLES.md
This `main` function is the entry point for the QR code pattern generation utility. It calls `createQRCodePattern()` to generate a random QR code-style SVG and PNG image, then prints a confirmation message.
```Go
func main() {
createQRCodePattern()
fmt.Println("✅ 二维码图案已创建完成")
}
```
--------------------------------
### Conventional Commits Specification
Source: https://github.com/hoonfeng/svg/blob/main/CONTRIBUTING.md
Defines the Conventional Commits specification for commit messages, including structure, types (feat, fix, docs, style, refactor, test, chore), and examples.
```APIDOC
[optional scope]:
[optional body]
[optional footer(s)]
Types:
- feat: New feature
- fix: Bug fix
- docs: Documentation update
- style: Code formatting
- refactor: Code refactoring
- test: Test related
- chore: Build or auxiliary tool changes
Examples:
feat(animation): add rotation animation support
fix(renderer): resolve memory leak in image rendering
docs: update API reference for text rendering
test(path): add unit tests for bezier curve parsing
```
--------------------------------
### Save SVG File with Go SVG
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICK_START.md
Demonstrates how to save the generated SVG canvas content to an SVG file. This snippet includes basic error handling to report any issues during the file saving process.
```Go
// 保存SVG文件 / Save SVG file
err := canvas.SaveSVG("my_drawing.svg")
if err != nil {
fmt.Printf("保存SVG失败: %v\n", err)
}
```
--------------------------------
### Demonstrate Color System in Go SVG Library
Source: https://github.com/hoonfeng/svg/blob/main/docs/BASIC_TUTORIAL.md
This Go function illustrates the color system capabilities of the `svg` library, including RGB, RGBA (with transparency), and grayscale colors. It shows how to apply these colors to rectangles and circles, demonstrating transparency through overlapping shapes and simulating a gradient effect using multiple colored rectangles. The generated SVG and PNG files are saved to disk.
```Go
func demonstrateColors() {
canvas := svg.New(700, 500)
// RGB颜色 / RGB colors
red := color.RGBA{255, 0, 0, 255}
green := color.RGBA{0, 255, 0, 255}
blue := color.RGBA{0, 0, 255, 255}
// RGBA颜色 (带透明度) / RGBA colors (with transparency)
transparentRed := color.RGBA{255, 0, 0, 128}
transparentGreen := color.RGBA{0, 255, 0, 128}
transparentBlue := color.RGBA{0, 0, 255, 128}
// 基本颜色示例 / Basic color examples
canvas.Rect(50, 50, 80, 60).Fill(red)
canvas.Rect(150, 50, 80, 60).Fill(green)
canvas.Rect(250, 50, 80, 60).Fill(blue)
// 透明度示例 / Transparency examples
canvas.Rect(50, 150, 80, 60).Fill(transparentRed)
canvas.Rect(150, 150, 80, 60).Fill(transparentGreen)
canvas.Rect(250, 150, 80, 60).Fill(transparentBlue)
// 重叠透明图形 / Overlapping transparent shapes
canvas.Circle(400, 100, 40).Fill(color.RGBA{255, 0, 0, 100})
canvas.Circle(430, 100, 40).Fill(color.RGBA{0, 255, 0, 100})
canvas.Circle(415, 130, 40).Fill(color.RGBA{0, 0, 255, 100})
// 灰度颜色 / Grayscale colors
for i := 0; i < 10; i++ {
gray := uint8(i * 25)
canvas.Rect(float64(50+i*50), 250, 40, 40).
Fill(color.RGBA{gray, gray, gray, 255})
}
// 颜色渐变效果 (通过多个图形模拟) / Color gradient effect (simulated with multiple shapes)
for i := 0; i < 20; i++ {
r := uint8(255 - i*12)
g := uint8(i * 12)
canvas.Rect(float64(50+i*25), 350, 25, 40).
Fill(color.RGBA{r, g, 0, 255})
}
canvas.SaveSVG("colors_demo.svg")
canvas.SavePNG("colors_demo.png")
}
```
--------------------------------
### Save JPEG File with Go SVG
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICK_START.md
Demonstrates how to save the generated SVG canvas content as a JPEG image file. This snippet includes basic error handling to report any issues during the image saving process.
```Go
// 保存JPEG文件 / Save JPEG file
err := canvas.SaveJPEG("my_drawing.jpg")
if err != nil {
fmt.Printf("保存JPEG失败: %v\n", err)
}
```
--------------------------------
### Save PNG File with Go SVG
Source: https://github.com/hoonfeng/svg/blob/main/docs/QUICK_START.md
Demonstrates how to save the generated SVG canvas content as a PNG image file. This snippet includes basic error handling to report any issues during the image saving process.
```Go
// 保存PNG文件 / Save PNG file
err := canvas.SavePNG("my_drawing.png")
if err != nil {
fmt.Printf("保存PNG失败: %v\n", err)
}
```