题目:
练习3.3: 按高度给每个多边形上色,使得峰顶呈红色,谷底呈蓝色。
练习3.4: 仿照1.7节的实例Lissajous的方法,构建一个Web服务器,计算并生成曲面,同时将SVG数据写入客户端。服务器必须如下设置Content-Type
报头。
w.Header().Set("Content-Type","image/svg+xml")
代码中囊括了gopl.io/ch1/lissajous
、gopl.io/ch1/server3
和gopl.io/ch3/surface
三个案例代码,重写了handler
函数和corner
函数的逻辑。
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
// See page 21.
// Server3 is an "echo" server that displays request parameters.
package main
import (
"fmt"
"log"
"math"
"net/http"
"strings"
)
const (
width, height = 600, 320 // canvas size in pixels
cells = 100 // number of grid cells
xyrange = 30.0 // axis ranges (-xyrange..+xyrange)
xyscale = width / 2 / xyrange // pixels per x or y unit
zscale = height * 0.4 // pixels per z unit
angle = math.Pi / 6 // angle of x, y axes (=30°)
)
var sin30, cos30 = math.Sin(angle), math.Cos(angle) // sin(30°), cos(30°)
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
//!+handler
// handler echoes the HTTP request.
func handler(w http.ResponseWriter, r *http.Request) {
var outResult string
var builder strings.Builder
w.Header().Set("Content-Type","image/svg+xml")
builder.WriteString(fmt.Sprintf("<svg xmlns='http://www.w3.org/2000/svg' "+
"style='stroke: grey; fill: white; stroke-width: 0.7' "+
"width='%d' height='%d'>", width, height))
for i := 0; i < cells; i++ {
for j := 0; j < cells; j++ {
ax, ay ,az:= corner(i+1, j)
bx, by ,bz:= corner(i, j)
cx, cy ,cz:= corner(i, j+1)
dx, dy ,dz:= corner(i+1, j+1)
if az < 0 && bz < 0 && cz < 0 && dz < 0 {
builder.WriteString(fmt.Sprintf("<polygon style='fill: blue' points='%g,%g %g,%g %g,%g %g,%g'/>\n",
ax, ay, bx, by, cx, cy, dx, dy))
} else {
builder.WriteString(fmt.Sprintf("<polygon style='fill: red' points='%g,%g %g,%g %g,%g %g,%g'/>\n",
ax, ay, bx, by, cx, cy, dx, dy))
}
}
}
builder.WriteString(fmt.Sprintf("</svg>"))
outResult = builder.String()
fmt.Println(outResult)
_, err := w.Write([]byte(outResult))
if err != nil {
return
}
}
func corner(i, j int) (float64, float64, float64) {
// Find point (x,y) at corner of cell (i,j).
x := xyrange * (float64(i)/cells - 0.5)
y := xyrange * (float64(j)/cells - 0.5)
// Compute surface height z.
z := f(x, y)
// Project (x,y,z) isometrically onto 2-D SVG canvas (sx,sy).
sx := width/2 + (x-y)*cos30*xyscale
sy := height/2 + (x+y)*sin30*xyscale - z*zscale
return sx, sy,z
}
func f(x, y float64) float64 {
r := math.Hypot(x, y) // distance from (0,0)
return math.Sin(r) / r
}
//!-handler