forked from wechat-miniprogram/miniprogram-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.js
132 lines (115 loc) · 2.31 KB
/
worker.js
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
const {fib} = require('../../../../util/util.js')
Page({
onShareAppMessage() {
return {
title: '多线程Worker',
path: 'page/API/pages/worker/worker'
}
},
data: {
res: '',
input: 35,
},
onLoad() {
this._worker = wx.createWorker('workers/fib/index.js')
},
onUnload() {
clearInterval(this.interval)
if (this._worker) this._worker.terminate()
},
bindInput(e) {
const val = Number(e.detail.value)
if (val > 40) return {value: 40}
if (Number.isNaN(val)) return {value: 33}
this.setData({
input: val
})
return undefined
},
reset() {
this.setData({res: ''})
},
compute() {
this.reset()
wx.showLoading({
title: '计算中...'
})
const t0 = +Date.now()
const res = fib(this.data.input)
const t1 = +Date.now()
wx.hideLoading()
this.setData({
res,
time: t1 - t0
})
},
multiThreadCompute() {
this.reset()
wx.showLoading({
title: '计算中...'
})
const t0 = +Date.now()
this._worker.postMessage({
type: 'execFunc_fib',
params: [this.data.input]
})
this._worker.onMessage((res) => {
if (res.type === 'execFunc_fib') {
wx.hideLoading()
const t1 = +Date.now()
this.setData({
res: res.result,
time: t1 - t0
})
}
})
},
onReady() {
this.position = {
x: 150,
y: 150,
vx: 2,
vy: 2
}
this.drawBall()
this.interval = setInterval(this.drawBall, 17)
},
drawBall() {
const p = this.position
p.x += p.vx
p.y += p.vy
if (p.x >= 300) {
p.vx = -2
}
if (p.x <= 7) {
p.vx = 2
}
if (p.y >= 300) {
p.vy = -2
}
if (p.y <= 7) {
p.vy = 2
}
const context = wx.createContext()
function ball(x, y) {
context.beginPath(0)
context.arc(x, y, 5, 0, Math.PI * 2)
context.setFillStyle('#1aad19')
context.setStrokeStyle('rgba(1,1,1,0)')
context.fill()
context.stroke()
}
ball(p.x, 150)
ball(150, p.y)
ball(300 - p.x, 150)
ball(150, 300 - p.y)
ball(p.x, p.y)
ball(300 - p.x, 300 - p.y)
ball(p.x, 300 - p.y)
ball(300 - p.x, p.y)
wx.drawCanvas({
canvasId: 'canvas',
actions: context.getActions()
})
},
})