Skip to content

Commit 41019cb

Browse files
Updated drawing with smoother transition while moving fast
1 parent 1afa3d2 commit 41019cb

File tree

1 file changed

+33
-14
lines changed

1 file changed

+33
-14
lines changed

scripts/app.js

Lines changed: 33 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -22,47 +22,66 @@ canvas.height = height;
2222

2323

2424
let isDrawing = false;
25-
let lastPositionX = null;
25+
let lastPosition = {x: null, y: null};
2626
canvas.addEventListener('mousemove', e => {
2727
if (isDrawing && sortingTimeout === null) {
28-
saveValue(e.offsetX, e.offsetY, lastPositionX);
28+
saveValue(e.offsetX, e.offsetY, lastPosition.x, lastPosition.y);
2929
}
30-
lastPositionX = e.offsetX;
30+
lastPosition.x = e.offsetX;
31+
lastPosition.y = e.offsetY;
3132
});
3233
window.addEventListener('mousedown', () => {
3334
isDrawing = true;
3435
});
3536
window.addEventListener('mouseup', () => {
3637
isDrawing = false;
37-
lastPositionX = null;
38+
lastPosition.x = null;
39+
lastPosition.y = null;
3840
});
3941

40-
function saveValue(x1, y1, x2) {
41-
x1 = Math.max(Math.min(width, x1), 0)
42+
function saveValue(x1, y1, x2, y2) {
43+
x1 = Math.max(Math.min(width, x1), 0);
4244
if (x2 == null) {
43-
x2 = x1
45+
x2 = x1;
4446
} else {
45-
x2 = Math.max(Math.min(width, x2), 0)
47+
x2 = Math.max(Math.min(width, x2), 0);
4648
}
47-
y1 = Math.max(Math.min(height, y1), 0)
4849

49-
let index1 = Math.min(Math.floor((x1 / width) * sizeSlider.value), sizeSlider.value - 1)
50+
y1 = Math.max(Math.min(height, y1), 0);
51+
if (y2 == null) {
52+
y2 = y1;
53+
} else {
54+
y2 = Math.max(Math.min(height, y2), 0);
55+
}
56+
57+
let index1 = Math.min(Math.floor((x1 / width) * sizeSlider.value), sizeSlider.value - 1);
5058
let index2 = Math.min(Math.floor((x2 / width) * sizeSlider.value), sizeSlider.value - 1);
5159
if (index1 > index2) {
5260
let saveValue = index1;
5361
index1 = index2;
5462
index2 = saveValue;
63+
saveValue = y2;
64+
y2 = y1;
65+
y1 = saveValue;
5566
}
56-
let value = y1 / height;
57-
for (; index1 <= index2; index1++) {
58-
arrayToSort[index1] = Math.min(1,value+Math.random()/500);
67+
68+
if (index1 === index2) {
69+
arrayToSort[index1] = randomiseValue(y1 / height);
70+
} else {
71+
for (let i = index1; i <= index2; i++) {
72+
arrayToSort[i] = randomiseValue(map_range(i, index1, index2, y1, y2) / height);
73+
}
5974
}
60-
draw()
75+
draw();
6176
if (sortIndex != null) {
6277
updateSortMethod(sortIndex);
6378
}
6479
}
6580

81+
function randomiseValue(value, divider = 500) {
82+
return Math.max(0.0001, Math.min(0.999999, value + Math.random() / divider) - Math.random() / divider);
83+
}
84+
6685

6786
const cnt = canvas.getContext("2d");
6887
cnt.font = "30px Arial";

0 commit comments

Comments
 (0)