/
injectCanvas.js
134 lines (116 loc) · 2.52 KB
/
injectCanvas.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
133
134
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.injectCanvas = injectCanvas;
exports.handleEvent = handleEvent;
/**
* @File : injectCanvas.js
* @Author :dtysky (dtysky@outlook.com)
* @Date : 7/02/2020, 7:26:37 PM
* @Description:
*/
var LISTENERS = {
click: [],
touchstart: [],
touchend: [],
touchmove: [],
touchcancel: []
};
function clearListeners() {
Object.keys(LISTENERS).forEach(function (key) {
LISTENERS[key] = [];
});
}
function injectCanvas(canvas, options) {
clearListeners();
var dpi = options.dpi;
canvas.style = {};
canvas.width = options.width * options.dpi;
canvas.height = options.height * options.dpi;
canvas.offsetWidth = options.width;
canvas.offsetHeight = options.height;
canvas.getBoundingClientRect = function () {
var bound = {
x: 0,
y: 0,
width: canvas.width / dpi,
height: canvas.height / dpi,
left: 0,
right: canvas.width / dpi,
top: 0,
bottom: canvas.height / dpi
};
return bound;
};
canvas.addEventListener = function (type, listener) {
if (!LISTENERS[type]) {
return;
}
LISTENERS[type].push(listener);
};
canvas.removeEventListener = function (type, listener) {
if (!LISTENERS[type]) {
return;
}
var index = LISTENERS[type].indexOf(listener);
if (index >= 0) {
LISTENERS[type].splice(index, 1);
}
};
wx.window.mainCanvas = canvas;
return canvas;
}
var noop = function noop() {};
function convertTouch(touch) {
var x = touch.x,
y = touch.y,
identifier = touch.identifier;
return {
identifier: identifier,
x: x,
y: y,
clientX: x,
clientY: y,
pageX: x,
pageY: y,
screenX: x,
screenY: y
};
}
function convertEvent(event) {
var e = {
preventDefault: noop,
stopPropagation: noop,
target: event.target,
currentTarget: event.currentTarget
};
if (event.type === 'tap') {
var _event$detail = event.detail,
x = _event$detail.x,
y = _event$detail.y;
e.x = x;
e.y = y;
e.clientX = x;
e.clientY = y;
e.offsetX = x;
e.offsetY = y;
e.pageX = x;
e.pageY = y;
e.screenX = x;
e.screenY = y;
} else {
e.changedTouches = event.changedTouches.map(convertTouch);
e.touches = event.touches.map(convertTouch);
}
return e;
}
function handleEvent(type, event) {
if (!LISTENERS[type]) {
return;
}
var e = convertEvent(event);
LISTENERS[type].forEach(function (cb) {
return cb(e);
});
}