-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsvg.go
41 lines (36 loc) · 1.21 KB
/
svg.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package avatar
import (
"bytes"
"text/template"
)
type SVGData struct {
Color1 string
Color2 string
Text string
Width int
Height int
FontSize float64
}
func CreateSVG(data SVGData) (string, error) {
t := template.Must(template.New("svg").Parse(`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="{{.Width}}" height="{{.Height}}" viewBox="0 0 {{.Width}} {{.Height}}" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<linearGradient id="avatar" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="{{.Color1}}"/>
<stop offset="100%" stop-color="{{.Color2}}"/>
</linearGradient>
</defs>
<g>
<rect fill="url(#avatar)" x="0" y="0" width="{{.Width}}" height="{{.Height}}"/>
{{if .Text}}<text x="50%" y="50%" alignment-baseline="central" dominant-baseline="middle" text-anchor="middle" fill="#fff" font-family="sans-serif" font-size="{{.FontSize}}">{{.Text}}</text>{{ end }}
</g>
</svg>
`))
var tpl bytes.Buffer
if err := t.Execute(&tpl, data); err != nil {
return "", err
}
result := tpl.String()
return result, nil
}