forked from krassowski/Anki-TouchScreen
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.html
589 lines (528 loc) · 17.7 KB
/
index.html
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
<html><head>
<script src="caligrapher/math.js"></script>
<script src="caligrapher/vector.js"></script>
<script src="caligrapher/curveFitting.js"></script>
<script src="caligrapher/bezier.js"></script>
<script src="caligrapher/corners.js"></script>
<script src="caligrapher/character.js"></script>
<script src="caligrapher/strokeDrawing.js"></script>
<script src="./perfectFreehand/packages/perfect-freehand/src/compliedJs/getStroke.js"></script>
</head><body style="background: rgb(255, 239, 213);"><div id="canvas_wrapper" style="touch-action: none;">
<canvas id="secondary_canvas" width="2562" height="1309" style="height: 1309px;"></canvas>
<canvas id="main_canvas" width="2562" height="1309" style="height: 1309px;"></canvas>
</div>
<div id="pencil_button_bar">
<input type="button" class="active" onclick="active=!active;switch_visibility()" id="ts_visibility_button" value="Hide" title="Toggle visiblity">
<input type="button" class="active" onclick="switch_perfect_freehand()" id="ts_perfect_freehand_button" value="Perf" title="Perfect Freehand">
<input type="button" class="" onclick="switch_drawing_mode()" value="漢字" id="ts_kanji_button" title="Toggle calligrapher">
<input type="button" onclick="ts_undo();" value="Undo" title="Undo the last stroke" id="ts_undo_button" class="active">
<input type="button" class="active" onclick="clear_canvas();" value="Clean" title="Clean whiteboard">
</div>
<style>
body {
overflow-x: hidden; /* Hide horizontal scrollbar */
}
body::-webkit-scrollbar {
display: none;
}
#canvas_wrapper, #main_canvas, #secondary_canvas
{
position:absolute;
top: 0px;
left: 0px;
z-index: 999;
}
#main_canvas, #secondary_canvas{
opacity: """ + str(ts_opacity) + """;
pointer-events:auto;
}
.night_mode #pencil_button_bar input[type=button].active
{
color: #fff!important;
}
#pencil_button_bar input[type=button].active
{
color: black!important;
}
#pencil_button_bar
{
position: fixed;
bottom: 1px;
right: 1px;
z-index: 1000;
font-family: "Arial Unicode MS", unifont, "Everson Mono", tahoma, arial;
}
#pencil_button_bar input[type=button]
{
border: 1px solid black;
margin: 0 1px;
float: left;
width: 120px!important;
font-size: 40px;
line-height: 40px;
height: 80px;
border-radius: 8px;
background-color: rgba(250,250,250,0.5)!important;
color: black;
color: #ccc!important;
}
.night_mode #pencil_button_bar input[type=button]{
background-color: rgba(10,10,10,0.5)!important;
border-color: #ccc;
color: #444!important;
text-shadow: 0 0 1px rgba(5, 5, 5, 0.9);
}
#canvas_wrapper
{
height: 100px
}
</style>
<script>
var visible = true;
var calligraphy = false;
var perfectFreehand = true;
var canvas = document.getElementById('main_canvas');
var secondary_canvas = document.getElementById('secondary_canvas');
var wrapper = document.getElementById('canvas_wrapper');
var ts_undo_button = document.getElementById('ts_undo_button');
var ts_visibility_button = document.getElementById('ts_visibility_button');
var ts_kanji_button = document.getElementById('ts_kanji_button');
var ts_perfect_freehand_button = document.getElementById('ts_perfect_freehand_button');
var ctx = canvas.getContext('2d');
var secondary_ctx = secondary_canvas.getContext('2d');
var arrays_of_points = [ ];
var line_type_history = [ ];
var perfect_cache = [ ];
var color = 'grey';
var line_width = 4;
var card = true;
canvas.onselectstart = function() { return false; };
secondary_canvas.onselectstart = function() { return false; };
wrapper.onselectstart = function() { return false; };
function switch_visibility()
{
stop_drawing();
if (visible)
{
canvas.style.display='none';
secondary_canvas.style.display=canvas.style.display;
ts_visibility_button.className = '';
}
else
{
ts_visibility_button.className = 'active';
canvas.style.display='block';
secondary_canvas.style.display=canvas.style.display;
}
visible = !visible;
}
function switch_perfect_freehand()
{
stop_drawing();
perfectFreehand = !perfectFreehand;
if(perfectFreehand)
{
ts_perfect_freehand_button.className = 'active';
}
else{
ts_perfect_freehand_button.className = '';
}
ts_redraw()
}
//Initialize event listeners at the start;
canvas.addEventListener("pointerdown", pointerDownLine);
canvas.addEventListener("pointermove", pointerMoveLine);
window.addEventListener("pointerup", pointerUpLine);
canvas.addEventListener("pointerdown", pointerDownCaligraphy);
canvas.addEventListener("pointermove", pointerMoveCaligraphy);
window.addEventListener("pointerup", pointerUpCaligraphy);
function switch_drawing_mode()
{
stop_drawing();
calligraphy = !calligraphy;
if(calligraphy)
{
ts_kanji_button.className = 'active';
}
else{
ts_kanji_button.className = '';
}
}
function switch_class(e,c)
{
var reg = new RegExp('(\\\s|^)' + c + '(\\s|$)');
if (e.className.match(new RegExp('(\\s|^)' + c + '(\\s|$)')))
{
e.className = e.className.replace(reg, '');
}
else
{
e.className += c;
}
}
function resize() {
var card = document.getElementsByClassName('card')[0]
ctx.canvas.width = window.innerWidth-1;
ctx.canvas.height = Math.max(
document.body.clientHeight,
window.innerHeight,
card ? card.scrollHeight : 0
)-1;
secondary_ctx.canvas.width = ctx.canvas.width;
secondary_ctx.canvas.height = ctx.canvas.height;
/* Get DPR with 1 as fallback */
var dpr = window.devicePixelRatio || 1;
dpr = dpr > 1 ? dpr : 1;
/* CSS size is the same */
canvas.style.height = ctx.canvas.height + 'px';
wrapper.style.width = ctx.canvas.width + 'px';
secondary_canvas.style.height = canvas.style.height;
secondary_canvas.style.width = canvas.style.width;
/* Increase DOM size and scale */
ctx.canvas.width *= dpr;
ctx.canvas.height *= dpr;
ctx.scale(dpr, dpr);
secondary_ctx.canvas.width *= dpr;
secondary_ctx.canvas.height *= dpr;
secondary_ctx.scale(dpr, dpr);
update_pen_settings()
}
window.addEventListener('resize', resize);
window.addEventListener('load', resize);
window.requestAnimationFrame(draw_last_line_segment);
var isPointerDown = false;
var mouseX = 0;
var mouseY = 0;
var active = true;
function update_pen_settings(){
ctx.lineJoin = ctx.lineCap = 'round';
ctx.lineWidth = line_width;
ctx.strokeStyle = color;
ctx.fillStyle = color;
secondary_ctx.lineJoin = ctx.lineJoin;
secondary_ctx.lineWidth = ctx.lineWidth;
secondary_ctx.strokeStyle = ctx.strokeStyle;
ts_redraw()
}
function ts_undo(){
stop_drawing();
switch (line_type_history.pop()) {
case 'C'://Calligraphy
strokes.pop();
break;
case 'L'://Simple Lines
var index = arrays_of_points.length-1
arrays_of_points.pop()
perfect_cache[index] = null;
break;
default:
//console.log("Unrecognized line type for undo")
break;
}
if(!line_type_history.length)
{
ts_undo_button.className = ""
}
ts_redraw()
}
function ts_redraw() {
pleaseRedrawEverything = true;
}
function ts_clear() {
pleaseRedrawEverything = true;
fullClear = true;
}
function clear_canvas()
{
//don't continue to put points into an empty array(pointermove) if clearing while drawing on the canvas
stop_drawing();
arrays_of_points = [];
perfect_cache = [];
strokes = [];
line_type_history = [];
ts_clear();
}
function stop_drawing() {
isPointerDown = false;
drawingWithPressurePenOnly = false;
}
function start_drawing() {
ts_undo_button.className = "active"
isPointerDown = true;
}
function draw_last_line_segment() {
window.requestAnimationFrame(draw_last_line_segment);
draw_upto_latest_point_async(nextLine, nextPoint, nextStroke);
}
var nextLine = 0;
var nextPoint = 0;
var nextStroke = 0;
var p1,p2,p3;
async function draw_path_at_some_point_async(startX, startY, midX, midY, endX, endY, lineWidth) {
ctx.beginPath();
ctx.moveTo((startX + (midX - startX) / 2), (startY + (midY - startY)/ 2));//midpoint calculation for x and y
ctx.quadraticCurveTo(midX, midY, (midX + (endX - midX) / 2), (midY + (endY - midY)/ 2));
ctx.lineWidth = lineWidth;
ctx.stroke();
};
function is_last_path_and_currently_drawn(i){
return (isPointerDown && arrays_of_points.length-1 == i)//the path is complete unless its the last of the array and the pointer is still down
}
function all_drawing_finished(i){
return (!isPointerDown && arrays_of_points.length-1 == i)//the path is complete unless its the last of the array and the pointer is still down
}
var pleaseRedrawEverything = false;
var fullClear = false;
async function draw_upto_latest_point_async(startLine, startPoint, startStroke){
//Don't keep redrawing the same last point over and over
//if(!pleaseRedrawEverything &&
//(startLine == arrays_of_points.length && startPoint == arrays_of_points[startLine-1].length) &&
//(startStroke == strokes.length)) return;
var fullRedraw = false;//keep track if this call started a full redraw to unset pleaseRedrawEverything flag later.
if (pleaseRedrawEverything) {// erase everything and draw from start
fullRedraw = true;
startLine = 0;
startPoint = 0;
startStroke = 0;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
for(var i = startLine; i < arrays_of_points.length; i++){ //Draw Lines
var needPerfectDraw = false;
nextLine = i;
///0,0,0; 0,0,1; 0,1,2 or x+1,x+2,x+3
//take the 2 previous points in addition to current one at the start of the loop.
p2 = arrays_of_points[i][startPoint > 1 ? startPoint-2 : 0];
p3 = arrays_of_points[i][startPoint > 0 ? startPoint-1 : 0];
for(var j = startPoint; j < arrays_of_points[i].length; j++){
nextPoint = j + 1;//track which point was last drawn so we can pick up where we left off on the next refresh.
p1 = p2;
p2 = p3;
p3 = arrays_of_points[i][j];
if(!perfectFreehand){
draw_path_at_some_point_async(p1[0],p1[1],p2[0],p2[1],p3[0],p3[1],p3[3]);
}
else {needPerfectDraw = true;}
}
if(needPerfectDraw) {
var path = !perfect_cache[i] || is_last_path_and_currently_drawn(i) ? new Path2D(
getFreeDrawSvgPath(
arrays_of_points[i],
!is_last_path_and_currently_drawn(i)
))
: perfect_cache[i]
perfect_cache[i] = path
ctx.fill(path);
}
if(all_drawing_finished(i)){
nextLine++;
nextPoint = 0;
}
startPoint = 0;
}
//Draw Calligraphy Strokes one by one starting from the given point
for(var i = startStroke; i < strokes.length; i++){
nextStroke = i+1;
strokes[i].draw(WEIGHT, ctx);
}
if (fullRedraw) {//finished full redraw, now can unset redraw all flag so no more full redraws until necesarry
pleaseRedrawEverything = false;
fullRedraw = false;
nextPoint = strokes.length == 0 ? 0 : nextPoint;//reset nest point if out of lines
nextStroke = strokes.length == 0 ? 0 : nextStroke;//reset for undo as well
if(fullClear){// start again from 0.
nextLine = 0;
nextStroke = 0;
fullClear = false;
}
}
}
var drawingWithPressurePenOnly = false; // hack for drawing with 2 main pointers when using a presure sensitive pen
function pointerDownLine(e) {
if (!e.isPrimary || calligraphy) { return; }
if (e.pointerType[0] == 'p') { drawingWithPressurePenOnly = true }
else if ( drawingWithPressurePenOnly) { return; }
if(!isPointerDown){
event.preventDefault();
arrays_of_points.push([[
e.offsetX,
e.offsetY,
e.pointerType[0] == 'p' ? e.pressure : 2,
e.pointerType[0] == 'p' ? (0.8 + e.pressure * line_width * 2) : line_width]]);
line_type_history.push('L');//Add new Simple line marker to shared history
start_drawing();
}
}
function pointerMoveLine(e) {
if (!e.isPrimary || calligraphy) { return; }
if (e.pointerType[0] != 'p' && drawingWithPressurePenOnly) { return; }
if (isPointerDown && active) {
arrays_of_points[arrays_of_points.length-1].push([
e.offsetX,
e.offsetY,
e.pointerType[0] == 'p' ? e.pressure : 2,
e.pointerType[0] == 'p' ? (0.8 + e.pressure * line_width * 2) : line_width]);
}
}
function pointerUpLine(e) {
/* Needed for the last bit of the drawing. */
if (!e.isPrimary || calligraphy) { return; }
if (e.pointerType[0] != 'p' && drawingWithPressurePenOnly) { return; }
if (isPointerDown && active) {
arrays_of_points[arrays_of_points.length-1].push([
e.offsetX,
e.offsetY,
e.pointerType[0] == 'p' ? e.pressure : 2,
e.pointerType[0] == 'p' ? (0.8 + e.pressure * line_width * 2) : line_width]);
}
stop_drawing();
if(perfectFreehand) ts_redraw();
}
document.addEventListener('keyup', function(e) {
// alt + Z or z
if ((e.keyCode == 90 || e.keyCode == 122) && e.altKey) {
e.preventDefault();
ts_undo();
}
// /
if (e.key === ".") {
clear_canvas();
}
// ,
if (e.key === ",") {
switch_visibility();
}
// alt + C or c
if ((e.key === "c" || e.key === "C") && e.altKey) {
e.preventDefault();
switch_drawing_mode();
}
// alt + X or x
if ((e.key === "x" || e.key === "X") && e.altKey) {
e.preventDefault();
switch_perfect_freehand();
}
})
/*
-------------------------------- Part of Caligrapher ------------------------------------------
Created By: August Toman-Yih
Git Repository: https://github.com/atomanyih/Calligrapher
*/
/* ------------------------------ script.js -----------------------------*/
//Modified to work with current canvas and board
//share the same canvas with pressure drawing
/*var canvas = document.getElementById('canvas'),
width = canvas.width,
height = canvas.height,
context = canvas.getContext("2d");
*/
//FIXME REORGANIZE EBERYTING
//--- constants ---//
RESOLUTION = 4;
WEIGHT = 15;
MIN_MOUSE_DIST = 5;
SPLIT_THRESHOLD = 8;
SQUARE_SIZE = 300;
//--- variables ---//
strokes = [];
points = [];
lines = [];
currentPath = [];
errPoint = [];
//use shared isPointerDown instead
//mouseDown = false;
// // share update function with pressure drawing so they don't clearRect eachother
// function update() {
// ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
// for(var i = 0; i<strokes.length; i++)
// strokes[i].draw(WEIGHT,ctx);
// }
function drawCurrentPath() {
secondary_ctx.beginPath();
secondary_ctx.moveTo(currentPath[0][0],currentPath[0][1]);
for(var i = 1; i<currentPath.length; i++) {
secondary_ctx.lineTo(currentPath[i][0],currentPath[i][1]);
}
secondary_ctx.stroke();
}
function pointerDownCaligraphy(e) {
if (!e.isPrimary || !calligraphy) { return; }
event.preventDefault();//don't paint anything when clicking on buttons, especially for undo to work
line_type_history.push('C');//Add new Caligragraphy line marker to shared history
start_drawing();
};
function pointerMoveCaligraphy(e) {
if (!e.isPrimary || !calligraphy) { return; }
if(isPointerDown) {
var mousePos = [e.offsetX, e.offsetY];
if(currentPath.length != 0) {
if(getDist(mousePos,currentPath[currentPath.length-1])>=MIN_MOUSE_DIST)
currentPath.push(mousePos);
drawCurrentPath();
} else
currentPath.push(mousePos);
}
};
function pointerUpCaligraphy(e) {
stop_drawing();
if (!e.isPrimary || !calligraphy || !currentPath.length) { return; }
points = currentPath;
var curves = fitStroke(points);
strokes.push(new Stroke(curves));
currentPath = [];// clear the array on pointer up so it doesnt enter new lines when clicking on buttons
secondary_ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);//clear the guide line in second canvas
};
// // handled in ts_undo()
// keydown = function(event) {
// var k = event.keyCode;
// console.log(k);
// if(k==68) {
// strokes.pop();
// }
// update();
// };
//
//window.addEventListener("keydown",keydown,true);
//
//update();
// ----------------------------------------- Perfect Freehand -----------------------------------------
function med(A, B) {
return [(A[0] + B[0]) / 2, (A[1] + B[1]) / 2];
}
// Trim SVG path data so number are each two decimal points. This
// improves SVG exports, and prevents rendering errors on points
// with long decimals.
const TO_FIXED_PRECISION = /(\s?[A-Z]?,?-?[0-9]*\.[0-9]{0,2})(([0-9]|e|-)*)/g;
function getSvgPathFromStroke(points){
if (!points.length) {
return "";
}
const max = points.length - 1;
return points
.reduce(
(acc, point, i, arr) => {
if (i === max) {
acc.push(point, med(point, arr[0]), "L", arr[0], "Z");
} else {
acc.push(point, med(point, arr[i + 1]));
}
return acc;
},
["M", points[0], "Q"],
)
.join(" ")
.replace(TO_FIXED_PRECISION, "$1");
}
function getFreeDrawSvgPath(inputPoints, complete) {
// Consider changing the options for simulated pressure vs real pressure
const options = {
simulatePressure: inputPoints[0][2] > 1,
size: line_width,
thinning: 0.6,
smoothing: 0.5,
streamline: 0.5,
easing: (t) => Math.sin((t * Math.PI) / 2), // https://easings.net/#easeOutSine
last: complete, // LastCommittedPoint is added on pointerup
};
return getSvgPathFromStroke(getStroke(inputPoints, options));
}
</script></body></html>