标签:iter 3.3 ica hit net port cells content xmlns
练习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, "<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, ok1, _ := corner(i+1, j)
bx, by, ok2, _ := corner(i, j)
cx, cy, ok3, _ := corner(i, j+1)
dx, dy, ok4, isPeak := corner(i+1, j+1)
if !(ok1 && ok2 && ok3 && ok4) {
continue
}
color := "#0000ff"
if isPeak {
color = "#ff0000"
}
fmt.Fprintf(w, "<polygon style=‘fill: %s‘ points=‘%g,%g %g,%g %g,%g %g,%g‘/>\n",
color, ax, ay, bx, by, cx, cy, dx, dy)
}
}
fmt.Fprintln(w, "</svg>")
}
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
}
//!-
标签:iter 3.3 ica hit net port cells content xmlns
原文地址:https://www.cnblogs.com/aboutblank/p/9763719.html