iT邦幫忙

DAY 27
1

蠻可愛的 Golang系列 第 27

弄個展示SVG的Server吧

  • 分享至 

  • xImage
  •  

昨天介紹了用Golang畫SVG,之前也有介紹用Golang寫HTTP Server.
今天來結合一下.

範例如下:

// hello79
package main

import (
	"fmt"
	"github.com/ajstarks/svgo"
	"log"
	"math/rand"
	"net/http"
	"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() {
	http.Handle("/circle", http.HandlerFunc(circle))
	err := http.ListenAndServe(":2003", nil)
	if err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}

func circle(w http.ResponseWriter, req *http.Request) {
	w.Header().Set("Content-Type", "image/svg+xml")

	rand.Seed(time.Now().UnixNano())

	width := 800
	height := 800
	aw := width / 2
	maxstroke := height / 10
	literactions := 50
	canvas := svg.New(w)
	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()
}

先執行本程式,讓他等待瀏覽器要求.

使用瀏覽器連線到 localhost:2003/circle
截圖如下:


上一篇
Golang也會畫SVG
下一篇
Golang 輸出PNG檔
系列文
蠻可愛的 Golang30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言