练习3.3是peak展示为红色,valley展示为蓝色。
练习3.4是将svg图像打印到浏览器中。
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. // License: https://creativecommons.org/licenses/by-nc-sa/4.0/ // See page 58. //!+ // Surface computes an SVG rendering of a 3-D surface function. package main import ( "fmt" "log" "math" "net/http" ) 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() { handler := func(w http.ResponseWriter, r *http.Request) { print(w) } http.HandleFunc("/", handler) log.Fatal(http.ListenAndServe("localhost:8000", nil)) } func print(w http.ResponseWriter) { w.Header().Set("Content-Type", "image/svg+xml") fmt.Fprintf(w, "") } func corner(i, j int) (float64, float64, bool, bool) { // 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. ok := true z := f(x, y) if math.IsNaN(z) { ok = false } isPeak := false if z > 0 { isPeak = true } // 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, ok, isPeak } func f(x, y float64) float64 { r := math.Hypot(x, y) // distance from (0,0) return math.Sin(r) / r } //!-