iT邦幫忙

DAY 26
0

蠻可愛的 Golang系列 第 26

Golang也會畫SVG

最近D3.js蠻流行的.
D3.js是使用SVG.
可愛的Golang也會畫SVG的.
我們來看一下例子吧.

// hello78
package main

import (
	"fmt"
	"github.com/ajstarks/svgo"
	"math/rand"
	"os"
	"time"
)

const arcfmt = "stroke:%s;stroke-opacity:%.2f;stroke-width:%dpx;fill:none"

var colors = []string{"red", "green", "blue", "white", "gray"}

func randarc(canvas *svg.SVG, aw, ah, sw int, f1, f2 bool) {
	begin := rand.Intn(aw)
	arclength := rand.Intn(aw)
	end := begin + arclength
	baseline := ah / 2
	al := arclength / 2
	cl := len(colors)
	canvas.Arc(begin, baseline, al, al, 0, f1, f2, end, baseline,
		fmt.Sprintf(arcfmt, colors[rand.Intn(cl)], rand.Float64(), rand.Intn(sw)))

}

func main() {
	rand.Seed(time.Now().UnixNano())

	width := 300
	height := 300
	aw := width / 2
	maxstroke := height / 10
	literactions := 50
	canvas := svg.New(os.Stdout)
	canvas.Start(width, height)
	canvas.Rect(0, 0, width, height)
	for i := 0; i < literactions; i++ {
		randarc(canvas, aw, height, maxstroke, false, true)
		randarc(canvas, aw, height, maxstroke, false, false)
	}
	canvas.End()
}

執行方式:

./hello78 > hello78.svg

檢視SVG圖形:


上一篇
分工合作
下一篇
弄個展示SVG的Server吧
系列文
蠻可愛的 Golang30

尚未有邦友留言

立即登入留言