-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDrawingContext.js
2221 lines (1932 loc) · 86.1 KB
/
DrawingContext.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
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
/*jshint laxcomma:true */
/* global CanvasRenderingContext2D, Integer, console */
"use strict";
// Last updated November 2011
// By Simon Sarris
// www.simonsarris.com
//
// Free to use and distribute at will
// So long as you are nice to people, etc
// Simple class for keeping track of the current transformation matrix
// For instance:
// var t = new Transform();
// t.rotate(5);
// var m = t.m;
// ctx.setTransform(m[0], m[1], m[2], m[3], m[4], m[5]);
// Is equivalent to:
// ctx.rotate(5);
// But now you can retrieve it :)
// Remember that this does not account for any CSS transforms applied to the canvas
function Transform(a,b,c,d,e,f) {
this.m = [a,b,c,d,e,f];
}
Transform.prototype.reset = function() {
this.m = [1,0,0,1,0,0];
};
Transform.prototype.toString = function(){
return "["+this.m[0]+","+this.m[1]+","+this.m[2]+","+this.m[3]+","+this.m[4]+","+this.m[5]+"]";
};
Transform.prototype.getScale = function(){
return [ parseFloat(Math.sqrt(Math.pow(this.m[0],2) + Math.pow(this.m[1],2)).toFixed(4))
,parseFloat(Math.sqrt(Math.pow(this.m[2],2) + Math.pow(this.m[3],2)).toFixed(4))];
};
Transform.prototype.getRotation = function(){
return parseFloat(Math.atan2(this.m[2], this.m[3]).toFixed(4));
};
Transform.prototype.getOrigin = function(){
return [parseFloat(this.m[4].toFixed(4)), parseFloat(this.m[5].toFixed(4))];
};
Transform.prototype.multiply = function(matrix) {
var m11 = this.m[0] * matrix[0] + this.m[2] * matrix[1];
var m12 = this.m[1] * matrix[0] + this.m[3] * matrix[1];
var m21 = this.m[0] * matrix[2] + this.m[2] * matrix[3];
var m22 = this.m[1] * matrix[2] + this.m[3] * matrix[3];
var dx = this.m[0] * matrix[4] + this.m[2] * matrix[5] + this.m[4];
var dy = this.m[1] * matrix[4] + this.m[3] * matrix[5] + this.m[5];
this.m[0] = m11;
this.m[1] = m12;
this.m[2] = m21;
this.m[3] = m22;
this.m[4] = dx;
this.m[5] = dy;
};
Transform.prototype.rotate = function(rad) {
var c = Math.cos(rad);
var s = Math.sin(rad);
var m11 = this.m[0] * c + this.m[2] * s;
var m12 = this.m[1] * c + this.m[3] * s;
var m21 = this.m[0] * -s + this.m[2] * c;
var m22 = this.m[1] * -s + this.m[3] * c;
this.m[0] = m11;
this.m[1] = m12;
this.m[2] = m21;
this.m[3] = m22;
};
Transform.prototype.translate = function(x, y) {
this.m[4] += this.m[0] * x + this.m[2] * y;
this.m[5] += this.m[1] * x + this.m[3] * y;
};
Transform.prototype.scale = function(sx, sy) {
this.m[0] *= sx;
this.m[1] *= sx;
this.m[2] *= sy;
this.m[3] *= sy;
};
Transform.prototype.transformPoint = function(px, py) {
var x = px;
var y = py;
px = x * this.m[0] + y * this.m[2] + this.m[4];
py = x * this.m[1] + y * this.m[3] + this.m[5];
return [px, py];
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// EXTENSIONS THAT THE OBJECTS *SHOULD* HAVE HAD ANYWAY
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// allow Strings to un-ligature themselves
String.prototype.removeLigatures = function(){
var result = "";
for(var i=0; i<this.length; i++){
if(this.charCodeAt(i) === 64260) { result+="ffl"; } // ffl
else if(this.charCodeAt(i) === 64259){ result+="ffi"; } // ffi
else if(this.charCodeAt(i) === 64258){ result+="fl"; } // fl
else if(this.charCodeAt(i) === 64257){ result+="fi"; } // fi
else if(this.charCodeAt(i) === 64256){ result+="ff"; } // ff
else if(this.charCodeAt(i) === 307) { result+="ij"; } // ij
else if(this.charCodeAt(i) === 230) { result+="ae"; } // æ
else if(this.charCodeAt(i) === 198) { result+="AE"; } // Æ
else if(this.charCodeAt(i) === 339) { result+="oe"; } // œ
else if(this.charCodeAt(i) === 338) { result+="OE"; } // Œ
else if(this.charCodeAt(i) === 7531) { result+="ue"; } // ᵫ
else if(this.charCodeAt(i) === 64262){ result+="st"; } // st
else { result+=this.charAt(i); }
}
return result;
};
Array.prototype.append = Array.prototype.concat;
Array.prototype.last = function(){
return this[this.length-1];
};
// hasAlpha : void -> Boolean
// if any pixel's alpha is less than 255, there IS an alpha channel used
CanvasRenderingContext2D.prototype.hasAlpha = function(){
var imgd = this.getImageData(0,0,this.canvas.width, this.canvas.height);
var pixels = imgd.data;
for (var i = 0; i<pixels.length; i+=4) {
if(pixels[i+3]<255){ return true; }
}
return false;
};
// isColor : void -> Boolean
// if every pixel's R==G==B, it's NOT a color image
CanvasRenderingContext2D.prototype.isColor = function(){
var imgd = this.getImageData(0,0,this.canvas.width, this.canvas.height);
var pixels = imgd.data;
for (var i = 0; i<pixels.length; i += 4) {
if(!(pixels[i]===pixels[i+1] && pixels[i+1]===pixels[i+2])){ return true; }
}
return false;
};
// isMonochrome : void -> Boolean
// if every pixel is anything besides 0 or 1, it's NOT a monochrome image
CanvasRenderingContext2D.prototype.isMonochrome = function(){
var imgd = this.getImageData(0,0,this.canvas.width, this.canvas.height);
var pixels = imgd.data;
for (var i = 0; i<pixels.length; i++) {
if(!(pixels[i]===0 || pixels[i]===255)){ return false; }
}
return true;
};
// use the DOM and CSS to get accurate and complete font metrics
// based off of the amazing work at http://mudcu.be/journal/2011/01/html5-typographic-metrics/#baselineCanvas
// PENDING CANVAS V5 API: http://www.whatwg.org/specs/web-apps/current-work/#textmetrics
CanvasRenderingContext2D.prototype._measureText = CanvasRenderingContext2D.prototype.measureText;
CanvasRenderingContext2D.prototype.measureText = function(str){
var metrics = this._measureText(str);
// setting up html used for measuring text-metrics
var container = document.createElement("div");
container.style.cssText = "position: absolute; top: 0px; left: 0px; zIndex=-1";
var parent = document.createElement("span");
parent.style.font = this.font; // use the same font settings as the context
var image = document.createElement("img"); // hack to get at CSS baselines properties
image.width = 42; image.height = 1; // we use a dataURL to reduce dependency on external image files
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWM4MbPgPwAGzwLR05RbqwAAAABJRU5ErkJggg==";
parent.appendChild(document.createTextNode(str));
parent.appendChild(image);
container.appendChild(parent);
document.body.appendChild(container);
// getting css equivalent of ctx.measureText() <-- overrides default width
image.style.display = "none";
parent.style.display = "inline";
metrics.width = parent.offsetWidth;
metrics.height = parent.offsetHeight;
// making sure super-wide text stays in-bounds
image.style.display = "inline";
var forceWidth = metrics.width + image.offsetWidth;
// capturing the "top" and "bottom" baseline
parent.style.cssText += "margin: 50px 0; display: block; width: " + forceWidth + "px";
metrics.topBaseline = image.offsetTop - 49;
metrics.bottomBaseline = metrics.topBaseline - parent.offsetHeight;
// capturing the "middle" baseline
parent.style.cssText += "line-height: 0; display: inline; width: " + forceWidth + "px";
metrics.middleBaseline = image.offsetTop + 1;
// derive other measurement from what we've got
metrics.alphaBaseline = 0;
metrics.descender = metrics.alphaBaseline - metrics.bottomBaseline;
metrics.topPadding = metrics.height - metrics.topBaseline;
document.body.removeChild(container); // clean up after ourselves
metrics.str = str; // debugging: let's keep the original string
metrics.font = this.font.cssString; // and font information lying around
return metrics;
};
// Transformation pipeline - initial values
CanvasRenderingContext2D.prototype.m = new Transform(1,0,0,1,0,0);
CanvasRenderingContext2D.prototype.scaleValues = [1.0, 1.0];
CanvasRenderingContext2D.prototype.rotation = 0;
CanvasRenderingContext2D.prototype.origin = [0, 0];
// Store original methods that we'll need to override
CanvasRenderingContext2D.prototype._rotate = CanvasRenderingContext2D.prototype.rotate;
CanvasRenderingContext2D.prototype._scale = CanvasRenderingContext2D.prototype.scale;
CanvasRenderingContext2D.prototype._transform = CanvasRenderingContext2D.prototype.transform;
// udpatePipeline : void -> void
// apply the stored transform matrix, translation and rotation values to the native transform matrix
CanvasRenderingContext2D.prototype.updatePipeline = function(){
// set the tranformation matrix
this.setTransform(this.m.m[0],this.m.m[1],this.m.m[2],this.m.m[3],this.m.m[4],this.m.m[5]);
this.translate(this.origin[0], this.origin[1]); // then translate
this._scale(this.scaleValues[0], this.scaleValues[1]); // then scale
this._rotate(this.rotation); // and finally rotate
};
// transform : Real Real Real Real Real -> void
// Adds a transformation by m to the drawing context’s current transformation.
CanvasRenderingContext2D.prototype.transform = function(m){
this.m.multiply(m);
this.updatePipeline();
};
// rotate : Angle -> void
// Adds a rotation of angle radians to the drawing context’s current transformation.
// DOES NOT change the separate rotation
CanvasRenderingContext2D.prototype.rotate = function(radians){
this.m.rotate(radians);
this.updatePipeline();
};
// scale : xScale yScale -> void
// Adds a scaling of x-scale in the X-direction and y-scale in the Y-direction to the drawing context’s current transformation.
// DOES NOT change the separate scale values
CanvasRenderingContext2D.prototype.scale = function(xScale, yScale){
this.m.scale(xScale, yScale);
this.updatePipeline();
};
// getTransformation : -> (Vector (Vector Real Real Real Real Real Real) Real Real Real Real Real)
CanvasRenderingContext2D.prototype.getTransformation = function(){
var scale = this.getScale();
var origin = this.getOrigin();
var rotation= this.getRotation();
return [this.m, origin[0], origin[1], scale[0], scale[1], rotation];
};
// setTransformation : T Real Real Real Real Real)-> void
// changes all transformation values
CanvasRenderingContext2D.prototype.setTransformation = function(m, xOrigin, yOrigin, xScale, yScale, rotation){
this.m = new Transform(m[0],m[1],m[2],m[3],m[4],m[5]);
this.origin = [xOrigin, yOrigin];
this.scaleValues = [xScale, yScale];
this.rotation = rotation;
this.updatePipeline();
};
// getRotation : void -> Real
CanvasRenderingContext2D.prototype.getRotation = function(){
return this.rotation;
};
// setRotation : Angle -> void
// changes the rotation, but NOT the transformation matrix
CanvasRenderingContext2D.prototype.setRotation = function(radians){
this.rotation = -radians;
this.updatePipeline();
};
// getScale : void -> Real Real
CanvasRenderingContext2D.prototype.getScale = function(){
return this.scaleValues;
};
// setScale : xScale yScale -> void
// changes the scale values, but NOT the transformation matrix
CanvasRenderingContext2D.prototype.setScale = function(xScale, yScale){
this.scaleValues = [xScale, yScale];
this.updatePipeline();
};
// getInitialMatrix : void -> (Vector xx xy yx yy xO yO)
CanvasRenderingContext2D.prototype.getInitialMatrix = function(){
return this.m;
};
// setInitialMatrix : (Vector real real real real real real) -> void
CanvasRenderingContext2D.prototype.setInitialMatrix = function(m){
this.m = new Transform(m[0],m[1],m[2],m[3],m[4],m[5]);
this.updatePipeline();
};
// setLineDash : [Numbers] -> void
if(!CanvasRenderingContext2D.prototype.setLineDash){
CanvasRenderingContext2D.prototype.setLineDash = function(dashes){
this.mozDash = this.webkitLineDash = dashes;
};
}
// ellipse : x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise -> void
// re-map the native implementation, if it exists. Otherwise install Ben Deane's arc code
// see https://github.com/xach/vecto/blob/master/arc.lisp
// TODO: take CCW into account!!
CanvasRenderingContext2D.prototype.ellipse = CanvasRenderingContext2D.prototype.ellipse ||
function(x, y, width, height, eta1, eta2, ccw){
console.log('fake ellipse method called with '+x+', '+y+', '+width+', '+height+', '+eta1+', '+eta2);
var that = this;
// set ccw to false by default
ccw = ccw || true;
// since the racket drawing spec puts 0.5PI at 12 o'clock, we treat eta2 as the
// amount to SUBTRACT from eta1, which properly translates the angle
eta2 = 2*Math.PI-eta2;
// make sure everything is within 0-2PI radians, and that eta1 is LARGER
eta1 = eta1 % (2*Math.PI); eta2 = eta2 % (2*Math.PI);
if(eta1 <= eta2){ eta1 += 2*Math.PI; }
// If start == end, it's a no-op
if(eta1 === eta2){ return; }
// set up variables needed by the approximateArc function
var a = width/2, b = height/2, cx = x+a, cy = y+b;
// take note that we haven't issues a moveTo yet
var movedTo = true;
// approximate the arc, going from max->min or min-max depending on ccw
approximateArc(cx, cy, a, b, eta1, eta2);
// approximate an arc from eta1 to eta2 within an error by subdividing
// return a list of beziers
function approximateArc(cx, cy, a, b, eta1, eta2){
var etamid;
if(eta1 < eta2){ throw "approximateArc: eta2 must be bigger than eta1"; }
else if(eta1-eta2 > Math.PI/2){
etamid = eta1 - Math.PI/2;
approximateArc(cx, cy, a, b, eta1, etamid);
approximateArc(cx, cy, a, b, etamid, eta2);
// if a single arc is NOT within acceptable error bounds (0.5),
// cut it in half and approximate the two sub-arcs
} else if(bezierError(a, b, eta1, eta2) >= 0.5){
etamid = (eta1+eta2)/2;
approximateArc(cx, cy, a, b, eta1, etamid);
approximateArc(cx, cy, a, b, etamid, eta2);
// otherwise, draw the darned thing!
} else {
var k = Math.tan((eta1-eta2)/2);
var alpha = Math.sin(eta1-eta2) * (Math.sqrt(4 + 3*k*k) - 1) / 3;
var p1x = cx + a*Math.cos(eta1),
p1y = cy + b*Math.sin(eta1),
p2x = cx + a*Math.cos(eta2),
p2y = cy + b*Math.sin(eta2),
c1x = p1x - (-a*Math.sin(eta1))*alpha,
c1y = p1y - b*Math.cos(eta1)*alpha,
c2x = p2x + -a*Math.sin(eta2)*alpha,
c2y = p2y + b*Math.cos(eta2)*alpha;
if(movedTo){ that.moveTo(p1x, p1y); movedTo = false;}
that.bezierCurveTo(c1x, c1y, c2x, c2y, p2x, p2y);
}
}
// compute the error of a cubic bezier that approximates an elliptical arc
// with radii a, b between angles eta1 and eta2
function bezierError(a, b, eta1, eta2){
// coefficients for error estimation: 0 < b/a < 1/4
var coeffs3Low = [
[[ 3.85268, -21.229, -0.330434, 0.0127842 ],
[ -1.61486, 0.706564, 0.225945, 0.263682 ],
[ -0.910164, 0.388383, 0.00551445, 0.00671814 ],
[ -0.630184, 0.192402, 0.0098871, 0.0102527 ]]
, [[ -0.162211, 9.94329, 0.13723, 0.0124084 ],
[ -0.253135, 0.00187735, 0.0230286, 0.01264 ],
[ -0.0695069, -0.0437594, 0.0120636, 0.0163087 ],
[ -0.0328856, -0.00926032, -0.00173573, 0.00527385 ]]
];
// coefficients for error estimation: 1/4 <= b/a <= 1
var coeffs3High = [
[[ 0.0899116, -19.2349, -4.11711, 0.183362 ],
[ 0.138148, -1.45804, 1.32044, 1.38474 ],
[ 0.230903, -0.450262, 0.219963, 0.414038 ],
[ 0.0590565, -0.101062, 0.0430592, 0.0204699 ]]
, [[ 0.0164649, 9.89394, 0.0919496, 0.00760802 ],
[ 0.0191603, -0.0322058, 0.0134667, -0.0825018 ],
[ 0.0156192, -0.017535, 0.00326508, -0.228157 ],
[ -0.0236752, 0.0405821, -0.0173086, 0.176187 ]]
];
var calcCTerm = function(i, ratio, etasum, arr){
var cTerm = 0;
for(var j=0; j<4; j++){
cTerm+= Math.cos(j*etasum) *
((Math.pow(arr[i][j][0]*ratio,2) + arr[i][j][1]*ratio) + arr[i][j][2]) / (arr[i][j][3]+ratio);
}
return cTerm;
};
var ratio = b/a;
var etadiff = eta2 - eta1;
var etasum = eta2 + eta1;
var coeffs = (ratio < 0.25)? coeffs3Low : coeffs3High;
return (((0.001*Math.pow(ratio,2)) + (4.98*ratio) + 0.207) / (ratio + 0.0067)) *
a * Math.pow(Math.e,(calcCTerm(0, ratio, etasum, coeffs)) +
(calcCTerm(1, ratio, etasum, coeffs) * etadiff));
}
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// COLOR AND COLORDB
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Color : [ Number Number Number ] -> Color
// Color : String -> Color
// implements color%, as defined in http://docs.racket-lang.org/draw/color_.html?q=dc
function Color(c){
var that = this;
var rgb = arguments;
if(arguments.length === 1){ rgb = colorDB.findColor(c); }// get RGB array, if it's not already one
that.r = rgb[0];
that.g = rgb[1];
that.b = rgb[2];
that.a = (rgb[3] === undefined)? 1 : rgb[3];
that.red = function(){return that.r;};
that.green = function(){return that.g;};
that.blue = function(){return that.b;};
that.alpha = function(){return that.a;};
function valid(v){return v>=0 && v<=255;}
that.ok = function(){
return valid(that.r) && valid(that.g) && valid(that.b) && that.alpha >=0 && that.alpha <=1;
};
that.set = function (r, g, b, a){
that.r = r;
that.g = g;
that.b = b;
that.a = a;
};
that.copyFrom = function (c){
that.set(c.red(), c.green(). c.blue(), c.alpha());
};
that.getRGBA = function(){
return "rgba("+that.r+", "+that.g+", "+that.b+", "+that.a+")";
};
return this;
}
// ColorDatabase : void -> this
// implements color-database%, as defined in http://docs.racket-lang.org/draw/color-database___.html
function ColorDatabase() {
this.colors = {};
// based on an awesome hack from http://stackoverflow.com/questions/1573053/javascript-function-to-convert-color-names-to-hex-codes
this.findColor = function(name){
// create and color a textarea, and use the browser to get the RGB values of that color
var color, probe = document.createElement("textarea");
probe.style.display = "none";
document.body.appendChild(probe);
probe.style.color = name;
if(window.getComputedStyle){
var style = window.getComputedStyle(probe, null);
var rgb = style.getPropertyCSSValue('color').getRGBColorValue();
color = [parseInt(rgb.red.cssText),
parseInt(rgb.green.cssText),
parseInt(rgb.blue.cssText)];
} else {
var hex = probe.set('value', '').createTextRange().queryCommandValue("ForeColor");
color = [Integer.valueOf( hex.substring( 1, 3 ), 16 ),
Integer.valueOf( hex.substring( 3, 5 ), 16 ),
Integer.valueOf( hex.substring( 5, 7 ), 16 ) ];
}
document.body.removeChild(probe);
return color;
};
return this;
}
var colorDB = new ColorDatabase();
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// DC-PATH
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// implements dc-path%, as defined by http://docs.racket-lang.org/draw/dc-path_.html
/*
* Each dc-path% has a single array of operations which specify an
* open sub-path (openPath), and an array of closed sub-paths (closedPaths)
* the object also tracks the min/max coordinates each time a path is modified, to easily retrieve bounding box info
*/
function dcPath(){
var that = this;
that.openPath = false;
that.closedPaths = [];
that.minX = null;
that.minY = null;
that.maxX = null;
that.maxY = null;
return this;
}
dcPath.prototype.toString = function(){
var str = "";
var printPath = function(path){
for(var i=0; i<path.length; i++){
str += "ctx."+path[i].f+"("+path[i].args.map(Math.round).join(",")+");\n";
}
};
// print out all the closed sub-paths first
for(var i=0; i<this.closedPaths.length; i++){ printPath(this.closedPaths[i]); }
printPath(this.openPath);
return str;
};
// append : dc-path -> dc-path
// append closed paths, and add that.open to this.openPath via a lineTo
dcPath.prototype.append = function(p){
this.closedPaths.append(p.closedPaths);
// if they both have open paths...
// connect the end of this one to the start of the other via lineTo
// then skip over the first instruction (ALWAYS a moveTo), since it becomes no-op
if(this.openPath && p.openPath){
this.lineTo(p.openPath[0].from);
for(var i=1; i< p.openPath.length; i++){ this.openPath.push(p.openPath[i]); }
// if this one has no open path, grab the other's
} else if(!this.openPath){
this.openPath = p.openPath;
}
// update bounding box args
this.minX = Math.min(this.minX, p.minX);
this.minY = Math.min(this.minY, p.minY);
this.maxX = Math.max(this.maxX, p.maxX);
this.maxY = Math.max(this.maxY, p.maxY);
};
// reverse : void -> void
// reverses all sub-paths
dcPath.prototype.reverse = function(){
var oldClosed = this.closedPaths;
var oldOpen = this.openPath;
this.reset();
var that = this;
// reverse a single sub-path
var reverseSubPath = function(subPath){
for(var i=subPath.length-1; i > -1; i--){
// close -> moveTo(from)
if(subPath[i].f === CanvasRenderingContext2D.prototype.closePath){
that.moveTo.apply(that, subPath[i].from);
// curveTo -> curveTo(from[x,y], c3[x,y], c2[x,y])
} else if(subPath[i].f === CanvasRenderingContext2D.prototype.bezierCurveTo){
var c2 = subPath[i].args.slice(2,4);
var c3 = subPath[i].args.slice(4);
var args = c3.append(c2).append(subPath[i].from);
that.curveTo.apply(that, args);
// lineTo -> lineTo(from)
} else if(subPath[i].f === CanvasRenderingContext2D.prototype.lineTo){
that.lineTo.apply(that, subPath[i].from);
// moveTo -> close()
} else if(subPath[i].f === CanvasRenderingContext2D.prototype.moveTo){
that.close();
}
}
};
// reverse every closed subPath (in reverse order)
for(var i=oldClosed.length-1; i>-1; i--){ reverseSubPath(oldClosed[i]); }
if(oldOpen){
var start = oldOpen.last().to;
that.moveTo(start[0], start[1]); // insert a moveTo operation to set the new start
reverseSubPath(oldOpen.slice(1));// reverse the path, ignoring the moveTo operation at index 0
}
};
// open : void -> Boolean
// if the openPath array is defined, and nonempty, we have an open path
dcPath.prototype.open = function(){
return (this.openPath.length > 0);
};
// open : void -> void
// set openPath to false, closePaths to an empty array
dcPath.prototype.reset = function(){
this.openPath = false;
this.closedPaths = [];
// nullify bounding box args
this.minX = null;
this.minY = null;
this.maxX = null;
this.maxY = null;
};
// get-bounding-box : void -> Real Real Real Real
// return the min and max coordinates
dcPath.prototype.getBoundingBox = function(){
return [Math.round(this.minX), Math.round(this.minY),
Math.round(this.maxX), Math.round(this.maxY)];
};
////////////////////////////////////// SUB-PATH PRIMITIVES /////////////////////////////////////
/*
* A sub-path is a defined as an array of *operations*, which are structs that include
* 1) f: the canvas path function
* 2) args: an array of arguments to the function
* 3) from: the ending x,y coordinates of the _previous_ operation
* 4) to: the ending x,y coordinates of the operation
*
* All sub-paths are made of these operations, which also update the bounding coordinates.
* There are FOUR operations: close(), curveTo(), lineTo() and moveTo(). Everything else
* is implemented based on calls to these four.
*/
// close : void -> void
// if there's an open path, add the closePath operation and push the array into closedPaths
dcPath.prototype.close = function(){
if(!this.openPath){ throw "exn:fail:contract -- there was no open path to close"; }
this.openPath.push({f: CanvasRenderingContext2D.prototype.closePath
,args: []
,from: this.openPath.last().to.slice(0) // pass by value, not ref
,to: this.openPath.last().to.slice(0)});
this.closedPaths.push(this.openPath);
this.openPath = false;
};
// curveTo : Real Real Real Real Real -> void
// Push the bezierCurveTo operation. ONLY valid if there's an open path.
dcPath.prototype.curveTo = function(cx1, cy1, cx2, cy2, x3, y3){
if(!this.openPath){ throw "exn:fail:contract -- there was no open path from which to extend a curve"; }
this.openPath.push({f: CanvasRenderingContext2D.prototype.bezierCurveTo
,args: [cx1, cy1, cx2, cy2, x3, y3]
,from: this.openPath.last().to.slice(0) // pass by value, not ref
,to: [x3, y3]});
// update bounding box args. from the spec:
// "the bounding box encloses the two control points as well as the start and end points"
this.minX = Math.min(this.minX, cx1, cx2, x3);
this.minY = Math.min(this.minY, cy1, cy2, y3);
this.maxX = Math.max(this.maxX, cx1, cx2, x3);
this.maxY = Math.max(this.maxY, cy1, cy2, y3);
};
// ellipseTo : Real Real Real Real Real Real -> void
// Push the bezierCurveTo operation. ONLY valid if there's an open path.
dcPath.prototype.arcTo = function(x, y, width, height, eta1, eta2){
if(!this.openPath){ throw "exn:fail:contract -- there was no open path from which to extend an arc"; }
// set up variables needed by the approximateArc function
var a = width/2, b = height/2, cx = x+a, cy = y+b,
k = Math.tan((eta1-eta2)/2);
var x2 = cx + a*Math.cos(eta2),
y2 = cy + b*Math.sin(eta2);
this.openPath.push({f: CanvasRenderingContext2D.prototype.ellipse
,args: [x, y, width, height, eta1, eta2]
,from: this.openPath.last().to.slice(0) // pass by value, not ref
,to: [x2, y2]});
// update bounding box args. from the spec:
// "the bounding box encloses the two control points as well as the start and end points"
this.minX = Math.min(this.minX, x, x+width);
this.minY = Math.min(this.minY, y, y+height);
this.maxX = Math.max(this.maxX, x, x+width);
this.maxY = Math.max(this.maxY, y, y+height);
};
// lineTo : Real Real -> void
// Push the lineeTo operation. ONLY valid if there's an open path.
dcPath.prototype.lineTo = function(x, y){
if(!this.openPath){ throw "exn:fail:contract -- there was no open path from which to extend a line"; }
this.openPath.push({f: CanvasRenderingContext2D.prototype.lineTo
,args: [x, y]
,from: this.openPath.last().to.slice(0) // pass by value, not ref
,to: [x, y]});
// update bounding box args
this.minX = Math.min(this.minX, x);
this.minY = Math.min(this.minY, y);
this.maxX = Math.max(this.maxX, x);
this.maxY = Math.max(this.maxY, y);
};
// moveTo : Real Real -> void
// closes an open path (if one exists) and starts a new one by pushing a moveTo operation
dcPath.prototype.moveTo = function(x, y){
if(this.openPath){ this.close(); }
this.openPath = [];
this.openPath.push({f: CanvasRenderingContext2D.prototype.moveTo
,args: [x, y]
,from: [x, y]
,to: [x, y]});
// update bounding box args
this.minX = Math.min(this.minX, x);
this.minY = Math.min(this.minY, y);
this.maxX = Math.max(this.maxX, x);
this.maxY = Math.max(this.maxY, y);
};
//////////////// Higher-level Subpath Operations /////////////////////////////
// lines : (Vector Points) Real Real -> void
// Push a series of lineTo operations. ONLY valid if there's an open path.
dcPath.prototype.lines = function(points, xOffset, yOffset){
if(!this.openPath){ throw "exn:fail:contract -- there was no open path from which to extend lines"; }
xOffset = xOffset || 0;
yOffset = yOffset || 0;
for(var i=0; i<points.length; i++){
this.lineTo(points[i].x+xOffset, points[i].y+yOffset);
}
};
// ellipse : Real Real Real Real -> void
// closes an open path (if one exists), pushes the necessary operations for an ellipse,
// then closes the subpath
dcPath.prototype.ellipse = function(x, y, width, height){
this.arc(x, y, width, height, 0, 2*Math.PI);
};
// arc : Real Real Real Real Real Real -> void
// closes an open path (if one exists), pushes the necessary operations for an ellipse,
// then closes the subpath
dcPath.prototype.arc = function(x, y, width, height, eta1, eta2){
if(this.openPath){ this.close(); }
this.moveTo(x, y);
this.arcTo(x, y, width, height, eta1, eta2);
};
// roundedRectangle : Real Real Real Real Integer -> void
dcPath.prototype.roundedRectangle = function(x, y, width, height, radius){
// check to make sure the radius is valid
// if radius is negative, use the absolute value as a proportion of the shortest side
var shortestSide = Math.min(width, height);
if(isNaN(radius) || (radius > 0.5*shortestSide) || (radius < -0.5)){ throw "Exn:fail:contract"; }
if(radius<0){ radius = shortestSide*Math.abs(radius); }
// from http://nacho4d-nacho4d.blogspot.com/2011/05/bezier-paths-rounded-corners-rectangles.html
var kappa = 0.5522848;
var co = kappa * radius; // control offset
this.moveTo(x+radius, y);
this.lineTo(x+width-radius, y);
this.curveTo(x+width-co, y, x+width, y+co, x+width, y+radius);
this.lineTo(x+width, y+height-radius);
this.curveTo(x+width, y+height-co, x+width-co, y+height, x+width-radius, y+height);
this.lineTo(x+radius, y+height);
this.curveTo(x+co, y+height, x, y+height-co, x, y+height-radius);
this.lineTo(x, y+radius);
this.curveTo(x, y+co, x+co, y, x+radius, y);
this.close();
};
// rectangle : Real Real Real Real -> void
// implemented in terms of roundedRectangle
dcPath.prototype.rectangle = function(x, y, width, height){
this.moveTo(x, y);
this.lineTo(x+width, y);
this.lineTo(x+width, y+height);
this.lineTo(x, y+height);
this.lineTo(x, y);
this.close();
};
//////////////// Operations that transform the path /////////////////////////////
// mapPoints : (Real Real -> void) -> void
// _stateful_ implementation of map, which apply a function f to every
// (x,y) pair in each Operation in each subpath
dcPath.prototype.mapPoints = function(f){
var from, to, args;
var applyf = function(f){
return function(op){
if(op.f === CanvasRenderingContext2D.prototype.closePath){
from = f(op.from);
to = f(op.to);
} else if(op.f === CanvasRenderingContext2D.prototype.bezierCurveTo){
var c1 = f(op.args.slice(0,2));
var c2 = f(op.args.slice(2,4));
var p = f(op.args.slice(4,6));
args = c1.append(c2).append(p);
from = f(op.from);
to = f(op.to);
} else if(op.f === CanvasRenderingContext2D.prototype.lineTo){
args = f(op.args);
from = f(op.from);
to = f(op.to);
} else if(op.f === CanvasRenderingContext2D.prototype.moveTo){
args = f(op.args);
from = f(op.from);
to = f(op.to);
}
return {f: op.f, args: args, from: from, to: to};
};
};
// make a function that knows how to apply f to any operation
var f_applier = applyf(f);
// map f over each operation in each closedPath
for(var i=0; i<this.closedPaths.length; i++) {
this.closedPaths[i] = this.closedPaths[i].map(f_applier);
}
// map f over each operation in the openPath
this.openPath = this.openPath.map(f_applier);
};
// scale : Real Real -> void
// scale all points in the path
dcPath.prototype.scale = function(xScale, yScale){
// scalePoint: [Real Real] -> void
var scalePoint = function(point){ return [point[0] * xScale, point[1] * yScale]; };
this.mapPoints(scalePoint);
};
// translate : Real Real -> void
// scale all points in the path
dcPath.prototype.translate = function(x, y){
var translatePoint = function(point){ return [point[0] + x, point[1] + y]; };
this.mapPoints(translatePoint);
};
// rotate : Real -> void
// rotate all points in the path
dcPath.prototype.rotate = function(radians){
var rotatePoint = function(point){
return [ Math.floor(Math.cos(radians) * point[0])
,Math.floor(Math.sin(radians) * point[1])];
};
this.mapPoints(rotatePoint);
};
//////////////// Given a 2D Context, Translate to a native path ///////////////////
// makeCanvasPath : CanvasRenderingContext2D -> void
// call each operation in a subpath with it's args, in the given CanvasRenderingContext
dcPath.prototype.makeCanvasPath = function(ctx){
var translateSubPath = function(subPath){
for(var i=0; i < subPath.length; i++){
subPath[i].f.apply(ctx, subPath[i].args);
}
};
// translate all closed sub-paths, then the open path
for(var i=0; i < this.closedPaths.length; i++){
translateSubPath(this.closedPaths[i]);
}
translateSubPath(this.openPath);
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// REGIONS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// implements region%, as defined by http://docs.racket-lang.org/draw/region_.html
/*
* Each region% is basically a B&W canvas, whose transformations are set
* at initialization or use by an associated DC. Bounding boxes are
* determined by using the dcPath& object to draw into these canvases
* and union/intersection/xoring is done through the canvas's native
* globalCompositeOperation
*/
function Region(dc){
this.dc = false; // dc is false if one has not been initialized
this.boundingBox = false; // bounding box is also false if there's no path or dc
// our hook into the native canvas element
this.ctx = document.createElement('canvas').getContext('2d');
this.ctx.fillStyle = 'black';
// if a DC is provided, copy its dimensions and start out clipping the whole rectangle
if(dc){
this.ctx.canvas.width = dc.getWidth();
this.ctx.canvas.height = dc.getHeight();
this.dc = dc;
this.setRectangle(0,0,dc.getWidth(), dc.getHeight());
}
var that = this;
// combine : Region String -> void
// private method that actually does the composition
// combine the two regions with the given globalCompositeOperation
// The dc of both regions must be the same, or they must both be unassociated to any dc.
function combine(rgn, operation){
if(that.dc !== rgn.dc){ throw "exn:fail:contract -- both regions must have the same DC to combine, or none at all"; }
that.ctx.globalCompositeOperation = operation;
that.ctx.drawImage(rgn.ctx.canvas,0,0); // let the browser do the actual gruntwork
// combine bounding boxes
that.boundingBox[0] = Math.min(that.boundingBox[0], rgn.boundingBox[0]);
that.boundingBox[1] = Math.min(that.boundingBox[1], rgn.boundingBox[1]);
that.boundingBox[2] = Math.max(that.boundingBox[2], rgn.boundingBox[2]);
that.boundingBox[2] = Math.max(that.boundingBox[3], rgn.boundingBox[3]);
}
// intersect : Region -> void
// Set the region to the intersection of itself and another region
this.intersect = function(rgn){ combine(rgn, "source-in"); };
// subtract : Region -> void
// Set the region to the subtraction of another region from itself
this.subtract = function(rgn){ combine(rgn, "destination-out"); };
// union : Region -> void
// Set the region to the union of another region from itself
this.union = function(rgn){ combine(rgn, "source-over"); };
// xor : Region -> void
// Set the region to the xor of another region from itself
this.xor = function(rgn){ combine(rgn, "xor"); };
// getDC : void -> dc / false
this.getDC = function(){return this.dc; };
return this;
}
// get-bounding-box : void -> Real Real Real Real
// if there's a dc, return the min and max coordinates
// otherwise, return the tracked box
Region.prototype.getBoundingBox = function(){
if(this.dc){ return [0, 0, this.dc.getWidth(), this.dc.getHeight()]; }
else{ return this.boundingBox; }
};
// in-region? : Real Real -> Boolean
Region.prototype.inRegion = function(x, y){
// if there's a DC, transform the point first and then check the bounds
if(this.dc){
var m = this.dc.getInitialMatrix(),
point = m.transformPoint(x, y);
return (point[0]>=0 && point[0]<=this.dc.width &&
point[1]>=0 && point[1]<=this.dc.height);
// if not, check the bounding box first, then the individual pixel
} else {
var box = this.boundingBox;
// if it's outside the box, return false
if(!box || (x < box[0] && x > box[2] && y < box[1] && y > box[3])){ return false;}
// otherwise, check the individual pixels of the bounding box
var image = this.ctx.getImageData(box[0], box[1], box[2], box[3]);
var pixels = image.data;
var index = y*box[2]+x; // flatten 2d index into a 1d index
return (pixels[4*index+3] === 255); // is the pixel not alpha'd out?
}
};
// isEmpty : void -> Boolean
// From the spec "Returns #t if the region is _approximately_ empty". If no DC is associated, throw an exception
Region.prototype.isEmpty = function(rgn){
if(!this.dc){ throw "exn:fail:contract -- a region must have an attached DC to check if empty"; }
else{
var box = this.boundingBox;
return box && (box[2] - box[0])*(box[3] - box[1]) === 0; // is the area of bounding box 0?
}
};
// setArc : Real Real Real Real Real -> void
// Set the region to the arc specificed by x,y,w,h,eta1 and eta2. (Use a path)
Region.prototype.setArc = function(x, y, w, h, eta1, eta2){
this.ctx.canvas.width = this.ctx.canvas.width;
var p = new dcPath();
p.arc(x, y, w, h, eta1, eta2); // make the path
p.makeCanvasPath(this.ctx); // draw it in the current context
this.ctx.fill(); // fill with black
this.boundingBox = p.getBoundingBox(); // update the new boundingBox
};