-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
wasm.go
82 lines (67 loc) · 1.84 KB
/
wasm.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// +build js,wasm
package main
import (
"bytes"
"encoding/base64"
"fmt"
"strconv"
"syscall/js"
"github.com/Chyroc/web"
"github.com/fogleman/gg"
)
func DrawEllipse(S float64) (string, error) {
dc := gg.NewContext(int(S), int(S))
dc.SetRGBA(0, 0, 0, 0.1)
for i := 0; i < 360; i += 15 {
dc.Push()
dc.RotateAbout(gg.Radians(float64(i)), S/2, S/2)
dc.DrawEllipse(S/2, S/2, S*7/16, S/8)
dc.Fill()
dc.Pop()
}
var buf = new(bytes.Buffer)
err := dc.EncodePNG(buf)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(buf.Bytes()), nil
}
func draw(imgDom web.HTMLElement, number int) {
img, err := DrawEllipse(float64(number * 10))
if err != nil {
web.Console.Log(err.Error())
} else {
imgDom.SetAttribute("src", fmt.Sprintf("data:image/png;base64,%s", img))
}
}
func main() {
var numberDoc = js.Global().Get("document").Call("getElementById", "number")
var plus = js.Global().Get("document").Call("getElementById", "plus")
var minus = js.Global().Get("document").Call("getElementById", "minus")
var imgDom = web.Document.GetElementById("img")
var number = 50
plus.Call("addEventListener", "click", js.NewCallback(func(args []js.Value) {
plus.Set("disabled", true)
minus.Set("disabled", true)
number++
fmt.Printf("change to %v\n", number)
go numberDoc.Set("innerHTML", strconv.Itoa(number))
draw(imgDom, number)
plus.Set("disabled", false)
minus.Set("disabled", false)
}))
minus.Call("addEventListener", "click", js.NewCallback(func(args []js.Value) {
plus.Set("disabled", true)
minus.Set("disabled", true)
number--
fmt.Printf("change to %v\n", number)
go numberDoc.Set("innerHTML", strconv.Itoa(number))
draw(imgDom, number)
plus.Set("disabled", false)
minus.Set("disabled", false)
}))
draw(imgDom, number)
plus.Set("disabled", false)
minus.Set("disabled", false)
web.Wait()
}