forked from Webstrates/tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpad.html
More file actions
1194 lines (973 loc) · 46.8 KB
/
pad.html
File metadata and controls
1194 lines (973 loc) · 46.8 KB
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<!-- Babel standalone, so external scripts are transformed to ES2015 compatible code -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.18.1/babel.min.js" integrity="sha256-ytbyYjrh7reluPwZgVEBSe7b4TLcLzsUi54AxrF/dDw=" crossorigin="anonymous"></script>
<!-- Hammer.js API -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js" integrity="sha256-eVNjHw5UeU0jUqPPpZHAkU1z4U+QFBBY488WvueTm88=" crossorigin="anonymous"></script>
<!-- Transformer.js API -->
<script type="text/javascript" src="https://rawgit.com/Webstrates/common-libs/dev/build/transformer.js"></script>
<!-- Google Material Font -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<!-- Create Transient Tool Palette -> external scripts will add tools to this tool palette -->
<script type="text/javascript">
webstrate.on("loaded", function() {
var toolPalette = document.createElement("transient");
toolPalette.setAttribute("id", "tool-palette");
document.body.appendChild(toolPalette);
});
</script>
<!-- Drawing Instrument -->
<script type="text/javascript" id="drawing-instrument">
webstrate.on("loaded", function() {;
(function() {
let svg;
let penColor = "black";
/**
* Calculates the mid-point between the two points A and B and then returns
* the mid-point.
*
* @param {any} pointA The point A.
* @param {any} pointB The point B.
* @returns The mid-point between point A and point B.
*/
const midPointBetween = (pointA, pointB) => {
return {
x: pointA.x + (pointB.x - pointA.x) / 2,
y: pointA.y + (pointB.y - pointA.y) / 2
};
}
/**
* Generates a path with regard to thickness of each point in path. This
* implementation was done by @clemens.
*
* @param {any} points Path points with x- and y-position and a thickness per
* point.
* @returns The path as string.
*/
const generatePath = (points) => {
const newPoints = [];
newPoints.push(points[0]);
for (let j = 1; j < points.length - 1; j++) {
let p1 = points[j - 1];
let p = points[j];
let p2 = points[j + 1];
let c = {
x: p2.x - p1.x,
y: p2.y - p1.y
};
let n = {
x: -c.y,
y: c.x
};
let len = Math.sqrt(n.x * n.x + n.y * n.y);
if (len == 0) continue;
let u = {
x: n.x / len,
y: n.y / len
};
newPoints.push({
x: p.x + u.x * p.thickness,
y: p.y + u.y * p.thickness
});
}
newPoints.push(points[points.length - 1]);
for (let j = points.length - 2; j > 0; j--) {
let p1 = points[j + 1];
let p = points[j];
let p2 = points[j - 1];
let c = {
x: p2.x - p1.x,
y: p2.y - p1.y
};
let n = {
x: -c.y,
y: c.x
};
let len = Math.sqrt(n.x * n.x + n.y * n.y);
if (len == 0) continue;
let u = {
x: n.x / len,
y: n.y / len
};
newPoints.push({
x: p.x + u.x * p.thickness,
y: p.y + u.y * p.thickness
});
}
let p1 = newPoints[0];
let p2 = newPoints[1];
let pathString = "M" + p1.x + " " + p1.y;
for (let j = 1; j < newPoints.length; j++) {
let midPoint = midPointBetween(p1, p2);
if (isNaN(p1.x) || isNaN(p1.y) || isNaN(midPoint.x) || isNaN(midPoint.y)) {
console.log("NaN");
}
pathString = pathString += " Q " + p1.x + " " + p1.y + " " + midPoint.x + " " + midPoint.y;
p1 = newPoints[j];
p2 = newPoints[j + 1];
}
return pathString;
}
const onPenDown = (pen, points, path) => {
const {
x,
y,
thickness
} = pen;
const point = {
x,
y,
thickness
};
points.push(point);
path.setAttribute("d", generatePath(points));
path.setAttribute("fill", pen.color);
svg.appendChild(path);
}
const onPenMove = (pen, points, path) => {
const {
x,
y,
thickness
} = pen;
const point = {
x,
y,
thickness
};
points.push(point);
path.setAttribute("d", generatePath(points));
}
const createToolPalette = () => {
const toolPalette = document.querySelector('#tool-palette');
const drawingTools = document.createElement("div");
drawingTools.setAttribute("class", "drawing-instrument-tools");
const clearCanvas = document.createElement("div");
clearCanvas.setAttribute("class", "instrument-tool clear-drawing-canvas");
clearCanvas.addEventListener("touchstart", event => {
Array.from(document.querySelectorAll("svg")).forEach(svg => {
svg.remove();
});
});
clearCanvas.addEventListener("click", event => {
Array.from(document.querySelectorAll("svg")).forEach(svg => {
svg.remove();
});
});
drawingTools.appendChild(clearCanvas);
const colors = [
"black",
"white",
"red",
"green",
"blue",
"orange",
"yellow"
];
const colorsElement = document.createElement("ul");
colorsElement.setAttribute("class", "colors");
drawingTools.appendChild(colorsElement);
let activeColor;
colors.forEach((color, index) => {
const colorElement = document.createElement("li");
colorElement.setAttribute("class", "instrument-tool color");
colorElement.style.background = color;
colorsElement.appendChild(colorElement);
colorElement.addEventListener("touchstart", event => {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
if (activeColor) {
activeColor.removeAttribute("active");
}
colorElement.setAttribute("active", "true");
activeColor = colorElement;
penColor = color;
}, true);
if (index === 0) {
penColor = color;
colorElement.setAttribute("active", "true");
activeColor = colorElement;
}
});
let isVisible = true;
drawingTools.show = () => {
drawingTools.style.opacity = 1.0;
drawingTools.style.pointerEvents = "all";
isVisible = true;
};
drawingTools.hide = () => {
drawingTools.style.pointerEvents = "none";
drawingTools.style.opacity = 0.0;
isVisible = false;
};
drawingTools.isVisible = () => {
return isVisible;
}
toolPalette.appendChild(drawingTools);
return drawingTools;
}
const toolPalette = createToolPalette();
const getPenPoint = (event, touch) => {
let transformable = event.target.closest('.transformable') || event.target.closest('.transformable-local');
// This is a hack and workaround because the outermost canvas uses the body as hammer target and therefore, we try
// to find the actual drawable.
if (!transformable) {
transformable = event.target.querySelector('.transformable-local');
}
if (transformable) {
let penPoint = new Transformer.Point(touch.clientX, touch.clientY);
return transformable.transformer.fromGlobalToLocal(penPoint);
}
return {
x: touch.clientX,
y: touch.clientY
};
}
const getPenThickness = (event, force) => {
let transformable = event.target.closest('.transformable') || event.target.closest('.transformable-local');
// This is a hack and workaround because the outermost canvas uses the body as hammer target and therefore, we try
// to find the actual drawable.
if (!transformable) {
transformable = event.target.querySelector('.transformable-local');
}
if (transformable) {
const globalScale = transformable.transformer.globalScale;
return (globalScale.x) * force * 3;
}
return force * 3;
}
const ns = "http://www.w3.org/2000/svg";
let path = null;
let points = [];
let timeout;
window.addEventListener("touchstart", event => {
if (event.touches.length !== 1) return;
let touch = event.touches[0];
if (touch.force === 0) return;
if (!toolPalette.isVisible()) {
toolPalette.show();
return;
}
if (event.target.closest('.instrument-tool')) return;
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
if (timeout) {
clearTimeout(timeout);
}
window.isManipulationEnabled = false;
let drawable = event.target.closest('.drawable');
if (!drawable) {
drawable = event.target.querySelector('.drawable');
}
svg = drawable.querySelector(':scope>svg');
if (!svg) {
svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
svg.setAttribute("xlink", "http://www.w3.org/1999/xlink");
svg.setAttribute("xmlns:xlink", "");
svg.setAttribute("class", "drawing-canvas")
drawable.insertBefore(svg, drawable.firstElementChild);
}
path = document.createElementNS(ns, "path");
points.length = 0;
const pen = getPenPoint(event, touch);
pen.thickness = getPenThickness(event, touch.force);
pen.color = penColor ? penColor : "black";
onPenDown(pen, points, path);
}, true);
window.addEventListener("touchmove", event => {
if (event.touches.length !== 1) return;
let touch = event.touches[0];
if (touch.force === 0) return;
if (event.target.closest('.instrument-tool')) {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
return;
}
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
const pen = getPenPoint(event, touch);
pen.thickness = getPenThickness(event, touch.force);
pen.color = penColor ? penColor : "black";
onPenMove(pen, points, path);
}, true);
// We will enable this code later to avoid unintended manipulation of
// the pad.
window.addEventListener("touchend", event => {
timeout = setTimeout(() => {
window.isManipulationEnabled = true;
}, 250);
}, true);
})();
});
</script>
<!-- Multi-Touch and Mouse Manipulation Instrument -->
<script type="text/javascript" id="manipulation-instrument">
webstrate.on("loaded", function() {
console.debug(`transformer-example.js`);
;
(function(exports) {
// Module object holding private variables.
const module = {};
// Prevent zooming on iOS >= 10
document.addEventListener('touchstart', function(event) {
if (event.touches.length > 1) {
event.preventDefault();
}
}, false);
// Global variable to enable manipulation events when true and disable events when false.
window.isManipulationEnabled = true;
const doTransform = (obj, local = false) => {
let hammerTarget = obj;
// Use different element to listen for manipulation events when hammer-target attribute is
// set.
if (obj.hasAttribute("hammer-target")) {
const targetSelector = obj.getAttribute("hammer-target");
hammerTarget = document.querySelector(targetSelector) || obj;
}
let actionsContainer;
// Add actions to an element when actionable class is present.
if (obj.classList.contains("actionable")) {
actionsContainer = document.createElement("transient");
actionsContainer.setAttribute("class", "actions-container");
const actions = document.createElement("ul");
actions.setAttribute("class", "actions");
actionsContainer.appendChild(actions);
const clearCanvasAction = document.createElement("li");
clearCanvasAction.setAttribute("class", "action clear-canvas-action");
// deleteAction.innerHTML = `<i class="material-icons md-24">delete_forever</i>`
clearCanvasAction.addEventListener("click", event => {
const svg = obj.querySelector(':scope>svg');
if (svg) {
svg.remove();
}
});
actions.appendChild(clearCanvasAction);
const deleteAction = document.createElement("li");
deleteAction.setAttribute("class", "action delete-action");
// deleteAction.innerHTML = `<i class="material-icons md-24">delete_forever</i>`
deleteAction.addEventListener("click", event => {
obj.remove();
});
actions.appendChild(deleteAction);
obj.appendChild(actionsContainer);
}
/**
* Bring target to front by changing zIndex style property.
*/
function updateZ(target) {
const transformables = document.querySelectorAll(".transformable");
const currentZ = Number(target.style.zIndex);
let maxZ = 1;
for (var i = 0; i < transformables.length; i++) {
maxZ = Number(transformables[i].style.zIndex) > maxZ ? Number(transformables[i].style.zIndex) : maxZ;
}
if (currentZ < maxZ) {
target.style.zIndex = maxZ + 1;
}
}
/**
* In case of a transformable-local do not update element's transform in element style but update
* its style as CSS style in the document head. The style is embedded in a transient tag element, so
* it is ignored by Webstrates and not synchronized.
*/
let callback = null;
if (local) {
const id = obj.id;
if (!id) {
throw Error(`A ".transformable-local" element needs an id to apply transforms locally.`);
}
const head = document.head;
const transient = document.createElement("transient");
const sheetStyle = document.createElement("style");
transient.appendChild(sheetStyle);
head.appendChild(transient);
callback = (matrix) => {
const cssTransform = matrix.toCss();
sheetStyle.innerHTML = `
#${id} {
-webkit-transform: ${cssTransform};
-moz-transform: ${cssTransform};
-ms-transform: ${cssTransform};
-o-transform: ${cssTransform};
transform: ${cssTransform};
}
`;
};
}
/**
* Bind element to transformer API. Once the binding is complete, then create a hammer manager to receive
* pan, rotate, and scale events. The transformer then manipulates the elements CSS transform style after
* applying individual transform.
*/
Transformer.bindElement(obj, callback).then(transformer => {
// // Alternatively, the transformer API binds the transformer object to the element.
// const transformer = obj.transformer;
const hammerManager = new Hammer.Manager(hammerTarget);
// If hammer target is different from source, then do a bi-directional binding.
// This will be used to identify the proper object to manipulate later in the
// isValidEvent function (see further down).
if (hammerTarget !== obj) {
hammerTarget.hammerSource = obj;
obj.hammerTarget = hammerTarget;
}
// Details on hammer.js can be found here: http://hammerjs.github.io
hammerManager.add(new Hammer.Pan({
threshold: 0,
pointers: 0
}));
hammerManager.add(new Hammer.Rotate({
threshold: 0
})).recognizeWith(hammerManager.get('pan'));
hammerManager.add(new Hammer.Pinch({
threshold: 0
})).recognizeWith([hammerManager.get('pan'), hammerManager.get('rotate')]);
// Create custom render transform for element.
// !!! Changing any of this code or re-order will effect rendering of element after manipulation.
const renderTransform = new Transformer.TransformGroup();
const scaleTransform = obj.scaleTransform = new Transformer.ScaleTransform();
const rotateTransform = obj.rotateTransform = new Transformer.RotateTransform();
const translateTransform = obj.translateTransform = new Transformer.TranslateTransform();
renderTransform.add(scaleTransform);
renderTransform.add(rotateTransform);
renderTransform.add(translateTransform);
obj.renderTransform = renderTransform;
// The center point, which is returned by hammer.js, is in screen coordinates. The following function
// will transform these screen coordinates to canvas coordinates and with respect to an element's transform
// and if necessary according to an element's transform hierarchy.
const adjustCenterPoint = point => {
let p = new Transformer.Point(point.x, point.y);
return obj.transformer.fromGlobalToLocal(p);
};
// Temporary variables.
let prevPoint = {
x: 0,
y: 0
};
let prevScale = 1.0;
let angleOffset = 0;
let prevAngle = 0;
// Actions attached to an object are scaled inverse to an element's transform hierarchy, so actions
// are always rendered in the "same" size.
const updateActionsScale = () => {
// Update actions container scale based on global scale of object. Thereby the actions
// do not grow or shrink with zooming.
if (actionsContainer) {
const scale = transformer.globalScale;
actionsContainer.style.transform = `scale(${scale.x, scale.y})`;
}
}
/**
* Check if event is a valid event.
*
* @param {any} event
* @returns
*/
const isValidEvent = (event) => {
// Global variable to turn manipulation off or on, e.g., to turn it off while stylus
// input and turn it on with a little delay to prevent jumping objects caused by the
// resting palm on the screen.
if (!window.isManipulationEnabled) {
return false;
}
let closestTarget = event.target.closest('.transformable') || event.target.closest('.transformable-local');
if (!closestTarget) {
let parent = event.target;
do {
if (parent.hammerSource) {
closestTarget = parent.hammerSource;
break;
}
}
while ((parent = parent.parentElement) !== null);
}
return closestTarget === obj;
}
// Consume event, so it does not get further propagated.
const consumeEvent = (event) => {
event.preventDefault();
event.srcEvent.preventDefault();
event.srcEvent.stopPropagation();
event.srcEvent.stopImmediatePropagation();
}
// Register pan handler.
hammerManager.on('panstart panmove panend', event => {
if (!isValidEvent(event)) return;
consumeEvent(event);
if (event.type === "panstart") {
updateZ(obj);
updateActionsScale();
if (event.maxPointers === 1) {
prevPoint = {
x: 0,
y: 0
};
}
return;
}
// if (event.type.indexOf("end") > -1) {
if (event.type === "panend" && event.isFinal) {
prevPoint = {
x: 0,
y: 0
};
transformer.complete();
return;
}
let deltaPoint = new Transformer.Point(event.deltaX, event.deltaY);
deltaPoint = transformer.fromGlobalToLocalDelta(deltaPoint);
const newX = (translateTransform.x - prevPoint.x) + deltaPoint.x;
const newY = (translateTransform.y - prevPoint.y) + deltaPoint.y;
translateTransform.set(newX, newY);
transformer.reapplyTransforms();
prevPoint = {
x: deltaPoint.x,
y: deltaPoint.y
};
});
// Register rotate handler.
hammerManager.on("rotatestart rotatemove", event => {
if (!isValidEvent(event)) return;
consumeEvent(event);
if (event.type === "rotatestart") {
angleOffset = event.rotation;
prevAngle = 0;
let centerPoint = adjustCenterPoint(event.center);
rotateTransform.centerPoint.x = centerPoint.x;
rotateTransform.centerPoint.y = centerPoint.y;
return;
}
// correct angle offset
event.rotation -= angleOffset;
const deltaAngle = (rotateTransform.angle - prevAngle) + event.rotation;
prevAngle = event.rotation;
rotateTransform.set(deltaAngle);
transformer.reapplyTransforms();
});
// Register scale handler.
hammerManager.on("pinchstart pinchmove", event => {
if (!isValidEvent(event)) return;
consumeEvent(event);
if (event.type === "pinchstart") {
prevScale = event.scale;
let centerPoint = adjustCenterPoint(event.center);
scaleTransform.centerPoint.x = centerPoint.x;
scaleTransform.centerPoint.y = centerPoint.y;
return;
}
const oldScale = scaleTransform.x;
const scaleX = (scaleTransform.x / prevScale) * event.scale;
const scaleY = (scaleTransform.y / prevScale) * event.scale;
prevScale = event.scale;
scaleTransform.set(scaleX, scaleY);
transformer.reapplyTransforms();
updateActionsScale();
});
let mouseManipulated = false;
// This is a workaround to complete last transform started by a mousewheel interaction.
hammerTarget.addEventListener("mousemove", event => {
if (mouseManipulated) {
transformer.complete();
mouseManipulated = false;
}
});
// Also allow object manipulation using mousewheel interaction. Hold down the ctrl key to
// scale an element and hold down the alt/option key to rotate an element.
hammerTarget.addEventListener("mousewheel", event => {
if (!event.ctrlKey && !event.altKey) return;
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
if (event.altKey) {
mouseManipulated = true;
const angle = (rotateTransform.angle - (event.wheelDelta / 10)) % 360;
rotateTransform.set(angle);
// Adjust translate transform to fit rotation point.
let centerPoint = {
x: event.clientX,
y: event.clientY
};
centerPoint = adjustCenterPoint(centerPoint);
rotateTransform.centerPoint.x = centerPoint.x;
rotateTransform.centerPoint.y = centerPoint.y;
transformer.reapplyTransforms();
} else if (event.ctrlKey) {
mouseManipulated = true;
// Normalize wheel to +1 or -1.
const wheel = event.wheelDelta / 120;
// Compute zoom factor.
const zoom = Math.exp(wheel * 0.02);
const newScale = scaleTransform.x * zoom;
scaleTransform.set(newScale, newScale);
// Adjust translate transform to fit zoom point.
let centerPoint = {
x: event.clientX,
y: event.clientY
};
centerPoint = adjustCenterPoint(centerPoint);
scaleTransform.centerPoint.x = centerPoint.x;
scaleTransform.centerPoint.y = centerPoint.y;
transformer.reapplyTransforms();
}
}, false);
});
}
/**
* Enable manipulation on new nodes that are added to the DOM.
*/
(function() {
const observerOptions = {
childList: true,
subtree: true
};
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
switch (mutation.type) {
case "childList":
Array.from(mutation.removedNodes).forEach(node => {
if (node.nodeType === 1 && node.transformer) {
node.transformer.destroy();
}
});
Array.from(mutation.addedNodes).forEach(node => {
if (node.nodeType === 1) {
if (!node.transformer && node.classList.contains("transformable")) {
doTransform(node);
}
Array.from(node.querySelectorAll('.transformable')).forEach(node => {
if (node.nodeType === 1 && !node.transformer) {
doTransform(node);
}
});
}
});
break;
}
});
});
observer.observe(document.body, observerOptions);
})();
// Enable manipulation on DOM nodes on page load.
Array.from(document.querySelectorAll('.transformable-local')).forEach(node => {
doTransform(node, true);
});
// Enable manipulation on DOM nodes on page load.
Array.from(document.querySelectorAll('.transformable')).forEach(node => {
doTransform(node);
});
}).call({}, window);
});
</script>
<!-- Picture Instrument -->
<script type="text/javascript" id="picture-instrument">
webstrate.on("loaded", function() {;
(function(exports) {
const onLoad = () => {
this.fileReader = new FileReader();
const imageTool = createDomNode();
}
const createDomNode = () => {
const toolPalette = document.querySelector('#tool-palette');
const pictureTools = document.createElement("div");
pictureTools.setAttribute("class", "picture-instrument-tools");
const inputWrapper = document.createElement("div");
inputWrapper.setAttribute("class", "instrument-tool add-picture-tool");
const label = document.createElement("label");
label.setAttribute("class", "input-button");
inputWrapper.appendChild(label);
this.input = document.createElement("input");
this.input.setAttribute("type", "file");
this.input.setAttribute("accept", "image/*");
this.input.addEventListener("change", event => {
uploadImage();
});
label.appendChild(this.input);
pictureTools.appendChild(inputWrapper);
toolPalette.appendChild(pictureTools);
return pictureTools;
}
const uploadImage = () => {
const file = this.input.files[0];
console.log(file);
this.fileReader.onload = (file) => {
processImage(file);
}
// Read in the image file as a data URL.
this.fileReader.readAsDataURL(file);
}
const processImage = (file) => {
const base64data = file.target.result;
const img = new Image();
let loaded = false;
img.addEventListener("load", () => {
if (loaded) return;
loaded = true;
createImageWebstrate(img);
});
img.src = base64data;
}
const createImageWebstrate = (img) => {
let width = img.width;
let height = img.height;
const max = Math.max(width, height);
const min = Math.min(width, height);
// Resize image when to large.
if (max > 800) {
let newWidth = width > height ? 400 : (min / max) * 400;
let newHeight = height > width ? 400 : (min / max) * 400;
width = newWidth;
height = newHeight;
const canvas = document.createElement('canvas');
canvas.width = newWidth;
canvas.height = newHeight;
const ctx = canvas.getContext('2d');
/// step 1 - resize to 50%
const oc = document.createElement('canvas');
const octx = oc.getContext('2d');
oc.width = img.width * 0.5;
oc.height = img.height * 0.5;
octx.drawImage(img, 0, 0, oc.width, oc.height);
/// step 2 - resize 50% of step 1
octx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5);
/// step 3, resize to final size
ctx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5, 0, 0, canvas.width, canvas.height);
img.src = canvas.toDataURL("image/png");
}
var boxDiv = document.createElement("div");
boxDiv.setAttribute("class", "transformable drawable actionable image-box");
boxDiv.style.left = "0px";
boxDiv.style.top = "0px";
boxDiv.style.width = `${width}px`;
boxDiv.style.height = `${height}px`;
const iframe = document.createElement("iframe");
window.webstrate.on("transcluded", (webstrateId) => {
if (iframe.contentWindow) {
const pathname = iframe.contentWindow.location.pathname;
if (iframe.getAttribute("src") !== pathname) {
iframe.src = pathname;
return;
}
iframe.contentDocument.body.appendChild(img);
}
});
boxDiv.appendChild(iframe);
const canvas = document.querySelector('#canvas');
canvas.appendChild(boxDiv);
iframe.src = "/new?prototype=pad-canvas-image";
iframe.style.pointerEvents = "none";
this.input.value = "";
}
onLoad();
}).call({}, window);
});
</script>
<style type="text/css">
html,
body {
margin: 0;
padding: 0;
}
body {
width: 100vw;
height: 100vh;
background: ghostwhite;
}
#canvas {
width: 100%;
height: 100%;
box-shadow: none;
overflow: visible;
}
#canvas>svg {
overflow: visible;
}
svg.drawing-canvas {
position: absolute;
width: 100%;
height: 100%;
z-index: 1;
pointer-events: none;
}
#canvas>svg.drawing-canvas {
width: 1px;
height: 1px;
overflow: visible;
}
#tool-palette {
position: fixed;