1 package main
2
3 import (
4 "fmt"
5 "math/rand"
6 "strconv"
7 "syscall/js"
8 "time"
9 )
10
11 const (
12 width = 400
13 height = 400
14 )
15
16 // 生成 0 - 1 的随机数
17 func getRandomNum() float32 {
18 rand.New(rand.NewSource(time.Now().UnixNano()))
19 n := float32(rand.Intn(10000))
20 return n / 10000.0
21 }
22
23 // 生成 0 - 10 的随机数
24 func getRandomNum2() float32 {
25 rand.New(rand.NewSource(time.Now().UnixNano()))
26 n := float32(rand.Intn(10000))
27 return n / 1000.0
28 }
29
30 // 使用 canvas 绘制随机图
31 func draw() {
32 var canvas js.Value = js.
33 Global().
34 Get("document").
35 Call("getElementById", "canvas")
36
37 var context js.Value = canvas.Call("getContext", "2d")
38
39 // reset
40 canvas.Set("height", height)
41 canvas.Set("width", width)
42 context.Call("clearRect", 0, 0, width, height)
43
44 // 随机绘制 50 条直线
45 var clineStyle = `rgba(%d, %d, %d, 0.5)`
46 for i := 0; i < 50; i++ {
47 lineStyle := fmt.Sprintf(clineStyle, 155+int(getRandomNum2()*10), 155+int(getRandomNum()*100), 155+int(getRandomNum()*100))
48 fmt.Println(lineStyle)
49 context.Call("beginPath")
50 context.Set("strokeStyle", lineStyle)
51 context.Call("moveTo", getRandomNum()*width, getRandomNum()*height)
52 context.Call("lineTo", getRandomNum()*width, getRandomNum()*height)
53 context.Call("stroke")
54 }
55
56 context.Set("font", "30px Arial")
57 context.Set("strokeStyle", "blue")
58 for i := 0; i < 10; i++ {
59 context.Call("strokeText", "hello wasm", (getRandomNum2()+1)*10+getRandomNum2()*10, (getRandomNum2()+1)*10+getRandomNum2()*50)
60 }
61 }
62
63 func registerCallbackFunc() {
64 cb := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
65 fmt.Println("button clicked")
66
67 num1 := getElementByID("num1").Get("value").String()
68 v1, err := strconv.Atoi(num1)
69 if nil != err {
70 fmt.Println("button clicked:", num1, err.Error())
71 jsAlert().Invoke(err.Error())
72 // panic(err)
73 return nil
74 }
75
76 num2 := getElementByID("num2").Get("value").String()
77 v2, err := strconv.Atoi(num2)
78 if nil != err {
79 fmt.Println("button clicked:", num2, err.Error())
80 // panic(err)
81 return nil
82 }
83
84 rlt := v1 + v2
85 getElementByID("rlt").Set("value", rlt)
86
87 return nil
88 })
89
90 getElementByID("compute").Call("addEventListener", "click", cb)
91 }
92
93 func getElementByID(id string) js.Value {
94 return js.Global().Get("document").Call("getElementById", id)
95 }
96
97 func jsAlert() js.Value {
98 return js.Global().Get("alert")
99 }
100
101 func main() {
102 fmt.Println("Hello, Go WebAssembly!")
103 draw()
104 // 通过js.Global().Get()拿到全局alert函数的引用
105 alert := js.Global().Get("alert")
106 // 调用alert.Invoke来调用alert函数
107 alert.Invoke("hello world")
108
109 registerCallbackFunc()
110 }