-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPieChartInput.js
346 lines (296 loc) · 10.2 KB
/
PieChartInput.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import React from 'react';
import PropTypes from 'prop-types';
const tau = 2 * Math.PI;
let canvas, ctx, center, radius, initialAngle,
colors, lineThickness, handleRadius;
let mouse = {
x: innerWidth / 2,
y: innerHeight / 2,
down: false,
touch: false
};
function distance(x1, y1, x2, y2) {
let xDiff = x2 - x1;
let yDiff = y2 - y1;
let d = Math.sqrt(Math.pow(xDiff, 2) + Math.pow(yDiff, 2));
return d;
};
function indexOfMax(arr) {
if (arr.length === 0) {
return -1;
}
let max = arr[0];
let maxIndex = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
maxIndex = i;
max = arr[i];
}
}
return maxIndex;
}
class PieChartInput extends React.Component {
constructor(props) {
super(props);
let valid = this.props.percents.reduce((a, b) => a + b, 0) === 1;
if (!valid) console.error('pie chart input: percent array must sum to 1');
this.state = {
percents: this.props.percents || [.3, .4, .3],
mouseOver: new Array(this.props.percents.length).fill(false),
grab: new Array(this.props.percents.length).fill(false),
angles: new Array(this.props.percents.length).fill(false),
globGrab: false,
};
this.canvasRef = React.createRef();
this.update = this.update.bind(this);
this.animate = this.animate.bind(this);
this.getPosFromAngle = this.getPosFromAngle.bind(this);
this.getMouseAngle = this.getMouseAngle.bind(this);
}
render() {
return (
<div className="pie-chart-input-container">
<canvas className="pie-input-canvas" ref={this.canvasRef} />
</div>
)
}
componentDidMount() {
canvas = this.canvasRef.current;
ctx = canvas.getContext('2d');
canvas.width = canvas.height = this.props.size || 300;
center = canvas.width / 2;
radius = center - 10;
initialAngle = this.props.initialAngle || 0;
colors = this.props.colors || new Array(this.state.percents.length).fill('white');
colors.push(colors.shift());
lineThickness = this.props.lineThickness || 2;
handleRadius = this.props.handleRadius || .04 * radius;
this.setState({
mouseOver: new Array(this.state.percents.length).fill(false),
grab: new Array(this.state.percents.length).fill(false),
globGrab: false,
});
// calculate angles from state.percents
let newAngles = [];
let oldAngle = initialAngle;
for (let i = 0; i < this.state.percents.length; i++) {
let angle = (this.state.percents[i] * tau) + oldAngle;
newAngles.push(angle);
oldAngle = angle;
}
this.setState({ angles: newAngles })
// mouse event listeners
window.addEventListener('mousemove',
function (event) {
let rect = canvas.getBoundingClientRect();
mouse.x = event.clientX - rect.left;
mouse.y = event.clientY - rect.top;
mouse.touch = false;
});
window.addEventListener('mousedown',
function () {
mouse.down = true;
mouse.touch = false;
});
window.addEventListener('mouseup',
function () {
mouse.down = false;
mouse.touch = false;
});
// touch event listeners
window.addEventListener('touchmove',
function (event) {
let touch = event.touches[0];
let rect = canvas.getBoundingClientRect();
mouse.x = touch.clientX - rect.left;
mouse.y = touch.clientY - rect.top;
mouse.touch = true;
});
window.addEventListener('touchstart',
function () {
mouse.down = true;
mouse.touch = true;
});
window.addEventListener('touchend',
function () {
mouse.down = false;
mouse.touch = true;
});
window.addEventListener('touchcancel',
function () {
mouse.down = false;
mouse.touch = true;
});
this.animate();
}
// calculate xy position from a given angle in radians
getPosFromAngle(angle) {
let xPos = center + radius * Math.cos(angle);
let yPos = center - radius * Math.sin(angle);
return ({ x: xPos, y: yPos });
}
// gets the angle of the mouse's position relative to center
// used for setting new angles when dragging
getMouseAngle() {
let r = distance(mouse.x, mouse.y, center, center);
let relativeMouseX = (mouse.x - center) / r;
let relativeMouseY = (-mouse.y + center) / r;
let mouseAngle = Math.atan2(relativeMouseY, relativeMouseX);
if (mouseAngle < 0) mouseAngle += tau;
// round to nearest percent
mouseAngle = (tau / 100) * Math.round(mouseAngle / (tau / 100));
return (mouseAngle);
}
// calculate percents array from an array of angles
getPercentsFromAngles(angles) {
let newPercents = [];
// push n-1 percents from angles array
for (let i = 0; i < angles.length - 1; i++) {
let newA = (angles[i + 1] - angles[i]);
if (newA < 0) newA += tau;
newPercents.push(newA / tau);
}
// calculate last percent by subtracting the total from 1
// this ensures that the percents always sum to 1
let sum = newPercents.reduce((a, b) => a + b, 0);
newPercents.unshift(1 - sum);
newPercents = newPercents.map(x => Math.round(x * 100) / 100);
// do not return if any percent is negative
// this prevents pie sections from overlapping
let valid = true;
newPercents.forEach(x => x < 0 ? valid = false : null);
if (valid) {
return newPercents;
}
}
update() {
// release all on mouseup
if (!mouse.down) {
this.setState({
mouseOver: new Array(this.state.mouseOver.length).fill(false),
grab: new Array(this.state.grab.length).fill(false),
globGrab: false
});
if (mouse.touch) {
mouse.x = mouse.y = 0;
}
}
// draw colors
// separate loop ensures colors are drawn underneath everything else
for (let i = 0; i < this.state.angles.length; i++) {
let currAngle = (-this.state.angles[i]) % tau;
let nextAngle = (-this.state.angles[i + 1]) % tau || (-this.state.angles[0]) % tau;
ctx.beginPath();
ctx.moveTo(center, center);
ctx.arc(center, center, radius, currAngle, nextAngle, true);
ctx.moveTo(center, center);
ctx.fillStyle = colors[i];
ctx.fill();
// edge case handling for all angles being equal
if (this.state.percents[i] === 1) {
ctx.arc(center, center, radius, 0, tau);
colors.unshift(colors.pop());
ctx.fillStyle = colors[i];
colors.push(colors.shift());
ctx.fill();
}
}
for (let i = 0; i < this.state.angles.length; i++) {
// draw radial line for each percent
ctx.beginPath();
ctx.moveTo(center, center);
let linePos = this.getPosFromAngle(this.state.angles[i]);
ctx.lineTo(linePos.x, linePos.y);
ctx.lineWidth = lineThickness;
ctx.stroke();
// draw handle
ctx.beginPath();
ctx.arc(linePos.x, linePos.y, handleRadius, 0, tau);
ctx.fillStyle = 'black';
ctx.fill();
// check for mouse down
if (mouse.down) {
// check for mouse over handle
let d = distance(mouse.x, mouse.y, linePos.x, linePos.y);
let handleSize = handleRadius;
if (mouse.touch) handleSize *= 4;
if (d < handleSize) {
let newMouseOver = this.state.mouseOver.slice();
newMouseOver[i] = true;
this.setState({ mouseOver: newMouseOver });
} else {
let newMouseOver = this.state.mouseOver.slice();
newMouseOver[i] = false;
this.setState({ mouseOver: newMouseOver });
}
// set appropriate grab boolean if mouse is down over a handle
if (this.state.mouseOver[i]) {
if (!this.state.globGrab) {
let newGrab = this.state.grab.slice();
newGrab[i] = true;
this.setState({
grab: newGrab,
globGrab: true
});
}
}
}
// grab and move line, recalculate angles and percents
if (this.state.grab[i]) {
let newAngles = this.state.angles.slice();
newAngles[i] = this.getMouseAngle();
// weird visual errors occur with angles of exactly 0 or exactly tau
// fudge it by adding a tiny amount to any angle of exactly 0
if (newAngles[i] === 0) newAngles[i] = tau + .0001;
let oldPercents = this.state.percents;
let newPercents = this.getPercentsFromAngles(newAngles);
if (newPercents) {
// edge case handling for all angles being equal
if (newPercents.some((x) => x === 1)) {
newPercents = new Array(newPercents.length).fill(0);
let index = indexOfMax(oldPercents);
newPercents[index] = 1;
}
this.setState({
angles: newAngles,
percents: newPercents
});
}
}
}
}
animate() {
requestAnimationFrame(this.animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
// update and check for changes
let oldAngles = this.state.angles.slice();
this.update();
let newAngles = this.state.angles.slice();
let changed = JSON.stringify(oldAngles) !== JSON.stringify(newAngles);
if (changed) {
if (typeof (this.props.callback) === "function") {
this.props.callback(this.state.percents);
}
}
// draw outline circle
ctx.beginPath();
ctx.arc(center, center, radius, 0, tau);
ctx.stroke();
// draw center circle
// this avoids visual errors with thicker lines
ctx.beginPath()
ctx.arc(center, center, lineThickness / 2, 0, tau);
ctx.fillStyle = 'black';
ctx.fill();
}
}
PieChartInput.propTypes = {
size: PropTypes.string,
percents: PropTypes.arrayOf(PropTypes.number),
initialAngle: PropTypes.number,
colors: PropTypes.arrayOf(PropTypes.string),
lineThickness: PropTypes.number,
handleRadius: PropTypes.number,
callback: PropTypes.func
}
export default PieChartInput;