forked from processing-js/processing-js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
processing.js
executable file
·2005 lines (1648 loc) · 54.5 KB
/
processing.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
/*
* Processing.js - John Resig (http://ejohn.org/)
* MIT Licensed
* http://ejohn.org/blog/processingjs/
*
* This is a port of the Processing Visualization Language.
* More information: http://processing.org/
*/
(function(){
this.Processing = function Processing( aElement, aCode) {
if ( typeof aElement == "string" )
aElement = document.getElementById( aElement );
var p = buildProcessing( aElement );
if ( aCode )
p.init( aCode );
return p;
};
function log() {
try {
console.log.apply( console, arguments );
} catch(e) {
try {
opera.postError.apply( opera, arguments );
} catch(e){}
}
}
var parse = Processing.parse = function parse( aCode, p ) {
// Angels weep at this parsing code :-(
// Remove end-of-line comments
aCode = aCode.replace(/\/\/ .*\n/g, "\n");
// Weird parsing errors with %
aCode = aCode.replace(/([^\s])%([^\s])/g, "$1 % $2");
// Simple convert a function-like thing to function
aCode = aCode.replace(/(?:static )?(\w+ )(\w+)\s*(\([^\)]*\)\s*{)/g, function(all, type, name, args) {
if ( name == "if" || name == "for" || name == "while" ) {
return all;
} else {
return "Processing." + name + " = function " + name + args;
}
});
// Attach import() to p{} bypassing JS command, allowing for extrernal library loading
aCode = aCode.replace(/import \(|import\(/g, "p.Import(");
// Force .length() to be .length
aCode = aCode.replace(/\.length\(\)/g, ".length");
// foo( int foo, float bar )
aCode = aCode.replace(/([\(,]\s*)(\w+)((?:\[\])+| )\s*(\w+\s*[\),])/g, "$1$4");
aCode = aCode.replace(/([\(,]\s*)(\w+)((?:\[\])+| )\s*(\w+\s*[\),])/g, "$1$4");
// float[] foo = new float[5];
aCode = aCode.replace(/new (\w+)((?:\[([^\]]*)\])+)/g, function(all, name, args) {
return "new ArrayList(" + args.slice(1,-1).split("][").join(", ") + ")";
});
aCode = aCode.replace(/(?:static )?\w+\[\]\s*(\w+)\[?\]?\s*=\s*{.*?};/g, function(all) {
return all.replace(/{/g, "[").replace(/}/g, "]");
});
// int|float foo;
var intFloat = /(\n\s*(?:int|float)(?:\[\])?(?:\s*|[^\(]*?,\s*))([a-z]\w*)(;|,)/i;
while ( intFloat.test(aCode) ) {
aCode = aCode.replace(new RegExp(intFloat), function(all, type, name, sep) {
return type + " " + name + " = 0" + sep;
});
}
// float foo = 5;
aCode = aCode.replace(/(?:static )?(\w+)((?:\[\])+| ) *(\w+)\[?\]?(\s*[=,;])/g, function(all, type, arr, name, sep) {
if ( type == "return" )
return all;
else
return "var " + name + sep;
});
// Fix Array[] foo = {...} to [...]
aCode = aCode.replace(/=\s*{((.|\s)*?)};/g, function(all,data) {
return "= [" + data.replace(/{/g, "[").replace(/}/g, "]") + "]";
});
// static { ... } blocks
aCode = aCode.replace(/static\s*{((.|\n)*?)}/g, function(all, init) {
// Convert the static definitons to variable assignments
//return init.replace(/\((.*?)\)/g, " = $1");
return init;
});
// super() is a reserved word
aCode = aCode.replace(/super\(/g, "superMethod(");
var classes = ["int", "float", "boolean", "string"];
function ClassReplace(all, name, extend, vars, last) {
classes.push( name );
var static = "";
vars = vars.replace(/final\s+var\s+(\w+\s*=\s*.*?;)/g, function(all,set) {
static += " " + name + "." + set;
return "";
});
// Move arguments up from constructor and wrap contents with
// a with(this), and unwrap constructor
return "function " + name + "() {with(this){\n " +
(extend ? "var __self=this;function superMethod(){extendClass(__self,arguments," + extend + ");}\n" : "") +
// Replace var foo = 0; with this.foo = 0;
// and force var foo; to become this.foo = null;
vars
.replace(/,\s?/g, ";\n this.")
.replace(/\b(var |final |public )+\s*/g, "this.")
.replace(/\b(var |final |public )+\s*/g, "this.")
.replace(/this.(\w+);/g, "this.$1 = null;") +
(extend ? "extendClass(this, " + extend + ");\n" : "") +
"<CLASS " + name + " " + static + ">" + (typeof last == "string" ? last : name + "(");
}
var matchClasses = /(?:public |abstract |static )*class (\w+)\s*(?:extends\s*(\w+)\s*)?{\s*((?:.|\n)*?)\b\1\s*\(/g;
var matchNoCon = /(?:public |abstract |static )*class (\w+)\s*(?:extends\s*(\w+)\s*)?{\s*((?:.|\n)*?)(Processing)/g;
aCode = aCode.replace(matchClasses, ClassReplace);
aCode = aCode.replace(matchNoCon, ClassReplace);
var matchClass = /<CLASS (\w+) (.*?)>/, m;
while ( (m = aCode.match( matchClass )) ) {
var left = RegExp.leftContext,
allRest = RegExp.rightContext,
rest = nextBrace(allRest),
className = m[1],
staticVars = m[2] || "";
allRest = allRest.slice( rest.length + 1 );
rest = rest.replace(new RegExp("\\b" + className + "\\(([^\\)]*?)\\)\\s*{", "g"), function(all, args) {
args = args.split(/,\s*?/);
if ( args[0].match(/^\s*$/) )
args.shift();
var fn = "if ( arguments.length == " + args.length + " ) {\n";
for ( var i = 0; i < args.length; i++ ) {
fn += " var " + args[i] + " = arguments[" + i + "];\n";
}
return fn;
});
// Fix class method names
// this.collide = function() { ... }
// and add closing } for with(this) ...
rest = rest.replace(/(?:public )?Processing.\w+ = function (\w+)\((.*?)\)/g, function(all, name, args) {
return "ADDMETHOD(this, '" + name + "', function(" + args + ")";
});
var matchMethod = /ADDMETHOD([\s\S]*?{)/, mc;
var methods = "";
while ( (mc = rest.match( matchMethod )) ) {
var prev = RegExp.leftContext,
allNext = RegExp.rightContext,
next = nextBrace(allNext);
methods += "addMethod" + mc[1] + next + "});"
rest = prev + allNext.slice( next.length + 1 );
}
rest = methods + rest;
aCode = left + rest + "\n}}" + staticVars + allRest;
}
// Do some tidying up, where necessary
aCode = aCode.replace(/Processing.\w+ = function addMethod/g, "addMethod");
function nextBrace( right ) {
var rest = right;
var position = 0;
var leftCount = 1, rightCount = 0;
while ( leftCount != rightCount ) {
var nextLeft = rest.indexOf("{");
var nextRight = rest.indexOf("}");
if ( nextLeft < nextRight && nextLeft != -1 ) {
leftCount++;
rest = rest.slice( nextLeft + 1 );
position += nextLeft + 1;
} else {
rightCount++;
rest = rest.slice( nextRight + 1 );
position += nextRight + 1;
}
}
return right.slice(0, position - 1);
}
// Handle (int) Casting
aCode = aCode.replace(/\(int\)/g, "0|");
// Remove Casting
aCode = aCode.replace(new RegExp("\\((" + classes.join("|") + ")(\\[\\])?\\)", "g"), "");
// Convert 3.0f to just 3.0
aCode = aCode.replace(/(\d+)f[^a-zA-Z0-9]/g, "$1");
// Force numbers to exist
//aCode = aCode.replace(/([^.])(\w+)\s*\+=/g, "$1$2 = ($2||0) +");
// Force characters-as-bytes to work
aCode = aCode.replace(/('[a-zA-Z0-9]')/g, "$1.charCodeAt(0)");
// Convert #aaaaaa into color
aCode = aCode.replace(/#([a-f0-9]{6})/ig, function(m, hex){
var num = toNumbers(hex);
return "DefaultColor(" + num[0] + "," + num[1] + "," + num[2] + ")";
});
function toNumbers( str ){
var ret = [];
str.replace(/(..)/g, function(str){
ret.push( parseInt( str, 16 ) );
});
return ret;
}
//log(aCode);
return aCode;
};
function buildProcessing( curElement ){
var p = {};
// Eval imported libraries
//for( var i = 0; var len = libs
// init
p.PI = Math.PI;
p.TWO_PI = 2 * p.PI;
p.HALF_PI = p.PI / 2;
p.P3D = 3;
p.CORNER = 0;
p.RADIUS = 1;
p.CENTER_RADIUS = 1;
p.CENTER = 2;
p.POLYGON = 2;
p.QUADS = 5;
p.TRIANGLES = 6;
p.POINTS = 7;
p.LINES = 8;
p.TRIANGLE_STRIP = 9;
p.TRIANGLE_FAN = 4;
p.QUAD_STRIP = 3;
p.CORNERS = 10;
p.CLOSE = true;
p.RGB = 1;
p.HSB = 2;
// mouseButton constants: values adjusted to come directly from e.which
// CONFLICT: LEFT and RIGHT are keyboard values in Processing already. - F1lT3R
// RESOLUTION: Extended Keyboard & Mouse variables
p.CENTER = 88888880;
p.CODED = 88888888;
p.UP = 88888870;
p.RIGHT = 88888871;
p.DOWN = 88888872;
p.LEFT = 88888869;
p.codedKeys = [69, 70, 71, 72];
// "Private" variables used to maintain state
var curContext = curElement.getContext("2d");
var doFill = true;
var doStroke = true;
var loopStarted = false;
var hasBackground = false;
var doLoop = true;
var looping = 0;
var curRectMode = p.CORNER;
var curEllipseMode = p.CENTER;
var inSetup = false;
var inDraw = false;
var curBackground = "rgba(204,204,204,1)";
var curFrameRate = 1000;
var curShape = p.POLYGON;
var curShapeCount = 0;
var curvePoints = [];
var curTightness = 0;
var opacityRange = 255;
var redRange = 255;
var greenRange = 255;
var blueRange = 255;
var pathOpen = false;
var mousePressed = false;
var keyPressed = false;
var firstX, firstY, secondX, secondY, prevX, prevY;
var curColorMode = p.RGB;
var curTint = -1;
var curTextSize = 12;
var curTextFont = "Arial";
var getLoaded = false;
var start = (new Date).getTime();
// println(), print()
p.ln = "";
// Glyph path storage for quick rendering
p.glyphTable = {};
// Global vars for tracking mouse position
p.pmouseX = 0;
p.pmouseY = 0;
p.mouseX = 0;
p.mouseY = 0;
p.mouseButton = 0;
p.mouseDown = false;
// Will be replaced by the user, most likely
p.mouseClicked = undefined;
p.mouseDragged = undefined;
p.mouseMoved = undefined;
p.mousePressed = undefined;
p.mouseReleased = undefined;
p.keyPressed = undefined;
p.keyReleased = undefined;
p.draw = undefined;
p.setup = undefined;
// The height/width of the canvas
p.width = curElement.width - 0;
p.height = curElement.height - 0;
// The current animation frame
p.frameCount = 0;
// Forced default color mode for #aaaaaa style
p.DefaultColor = function ( aValue1, aValue2, aValue3) {
var tmpColorMode = curColorMode;
curColorMode = p.RGB;
var c = p.color( ((aValue1 / 255) * redRange), ((aValue2 / 255) * greenRange), ((aValue3 / 255) * blueRange));
curColorMode = tmpColorMode;
return c;
}
p.ajax=function(url){
if(window.XMLHttpRequest){AJAX=new XMLHttpRequest();}
else{AJAX=new ActiveXObject("Microsoft.XMLHTTP");}
if(AJAX){
AJAX.open("GET",url,false);
AJAX.send(null);
return AJAX.responseText;
}else{return false;}
}
p.Import=function Import(lib){
eval(p.ajax(lib));
}
// Load a file or URL into strings
p.loadStrings = function loadStrings(url) {
return p.ajax(url).split("\n");
};
// In case I ever need to do HSV conversion:
// http://srufaculty.sru.edu/david.dailey/javascript/js/5rml.js
p.color = function color( aValue1, aValue2, aValue3, aValue4 ) {
var aColor = "";
if ( arguments.length == 3 ) {
aColor = p.color( aValue1, aValue2, aValue3, opacityRange );
} else if ( arguments.length == 4 ) {
var a = aValue4 / opacityRange;
a = isNaN(a) ? 1 : a;
if ( curColorMode == p.HSB ) {
var rgb = HSBtoRGB(aValue1, aValue2, aValue3);
var r = rgb[0], g = rgb[1], b = rgb[2];
} else {
var r = getColor(aValue1, redRange);
var g = getColor(aValue2, greenRange);
var b = getColor(aValue3, blueRange);
}
aColor = "rgba(" + r + "," + g + "," + b + "," + a + ")";
} else if ( typeof aValue1 == "string" ) {
aColor = aValue1;
if ( arguments.length == 2 ) {
var c = aColor.split(",");
c[3] = (aValue2 / opacityRange) + ")";
aColor = c.join(",");
}
} else if ( arguments.length == 2 ) {
aColor = p.color( aValue1, aValue1, aValue1, aValue2 );
} else if ( typeof aValue1 == "number" ) {
aColor = p.color( aValue1, aValue1, aValue1, opacityRange );
} else {
aColor = p.color( redRange, greenRange, blueRange, opacityRange );
}
// HSB conversion function from Mootools, MIT Licensed
function HSBtoRGB(h, s, b) {
h = (h / redRange) * 360;
s = (s / greenRange) * 100;
b = (b / blueRange) * 100;
var br = Math.round(b / 100 * 255);
if (s == 0){
return [br, br, br];
} else {
var hue = h % 360;
var f = hue % 60;
var p = Math.round((b * (100 - s)) / 10000 * 255);
var q = Math.round((b * (6000 - s * f)) / 600000 * 255);
var t = Math.round((b * (6000 - s * (60 - f))) / 600000 * 255);
switch (Math.floor(hue / 60)){
case 0: return [br, t, p];
case 1: return [q, br, p];
case 2: return [p, br, t];
case 3: return [p, q, br];
case 4: return [t, p, br];
case 5: return [br, p, q];
}
}
}
function getColor( aValue, range ) {
return Math.round(255 * (aValue / range));
}
return aColor;
}
p.red = function( aColor ) {
return parseInt( verifyChannel(aColor).slice(5) );
};
p.green = function( aColor ) {
return parseInt( verifyChannel(aColor).split(",")[1] );
};
p.blue = function( aColor ) {
return parseInt( verifyChannel(aColor).split(",")[2] );
};
p.alpha = function( aColor ) {
return parseInt( parseFloat(verifyChannel(aColor).split(",")[3])*255 );
};
function verifyChannel(aColor){
if(aColor.constructor == Array){
return aColor;
} else {
return p.color(aColor);
}
}
// Added lerpColor() - F1LT3R - 08.11.14
p.lerpColor = function lerpColor( c1, c2, amt ){
// Get RGBA values for Color 1 to floats
var colors1 = p.color(c1).split(",");
var r1 = parseInt( colors1[0].split("(")[1] );
var g1 = parseInt( colors1[1] );
var b1 = parseInt( colors1[2] );
var a1 = parseFloat( colors1[3].split(")")[0] );
// Get RGBA values for Color 2 to floats
var colors2 = p.color(c2).split(",");
var r2 = parseInt( colors2[0].split("(")[1] );
var g2 = parseInt( colors2[1] );
var b2 = parseInt( colors2[2] );
var a2 = parseFloat( colors2[3].split(")")[0] );
// Return lerp value for each channel, INT for color, Float for Alpha-range
var r = parseInt( p.lerp(r1, r2, amt) );
var g = parseInt( p.lerp(g1, g2, amt) );
var b = parseInt( p.lerp(b1, b2, amt) );
var a = parseFloat( p.lerp(a1, a2, amt) );
aColor = "rgba(" + r + "," + g + "," + b + "," + a + ")";
return aColor;
}
p.nf = function( num, pad ) {
var str = "" + num;
while ( pad - str.length )
str = "0" + str;
return str;
};
p.AniSprite = function( prefix, frames ) {
this.images = [];
this.pos = 0;
for ( var i = 0; i < frames; i++ ) {
this.images.push( prefix + p.nf( i, ("" + frames).length ) + ".gif" );
}
this.display = function( x, y ) {
p.image( this.images[ this.pos ], x, y );
if ( ++this.pos >= frames )
this.pos = 0;
};
this.getWidth = function() {
return getImage(this.images[0]).width;
};
this.getHeight = function() {
return getImage(this.images[0]).height;
};
};
function buildImageObject( obj ) {
var pixels = obj.data;
var data = p.createImage( obj.width, obj.height );
if ( data.__defineGetter__ && data.__lookupGetter__ && !data.__lookupGetter__("pixels") ) {
var pixelsDone;
data.__defineGetter__("pixels", function() {
if ( pixelsDone )
return pixelsDone;
pixelsDone = [];
for ( var i = 0; i < pixels.length; i += 4 ) {
pixelsDone.push( p.color(pixels[i], pixels[i+1], pixels[i+2], pixels[i+3]) );
}
return pixelsDone;
});
} else {
data.pixels = [];
for ( var i = 0; i < pixels.length; i += 4 ) {
data.pixels.push( p.color(pixels[i], pixels[i+1], pixels[i+2], pixels[i+3]) );
}
}
return data;
}
p.createImage = function createImage( w, h, mode ) {
var data = {};
data.width = w;
data.height = h;
data.data = [];
if ( curContext.createImageData ) {
data = curContext.createImageData( w, h );
}
data.pixels = new Array( w * h );
data.get = function(x,y) {
return this.pixels[w*y+x];
};
data._mask = null;
data.mask = function(img) {
this._mask = img;
};
data.loadPixels = function(){};
data.updatePixels = function(){};
return data;
};
p.createGraphics = function createGraphics( w, h ) {
var canvas = document.createElement("canvas");
var ret = buildProcessing( canvas );
ret.size( w, h );
ret.canvas = canvas;
return ret;
};
p.beginDraw = function beginDraw(){};
p.endDraw = function endDraw(){};
p.tint = function tint( rgb, a ) {
curTint = a;
};
function getImage( img ) {
if ( typeof img == "string" ) {
return document.getElementById(img);
}
if ( img.img || img.canvas ) {
return img.img || img.canvas;
}
for ( var i = 0, l = img.pixels.length; i < l; i++ ) {
var pos = i * 4;
var c = (img.pixels[i] || "rgba(0,0,0,1)").slice(5,-1).split(",");
img.data[pos] = parseInt(c[0]);
img.data[pos+1] = parseInt(c[1]);
img.data[pos+2] = parseInt(c[2]);
img.data[pos+3] = parseFloat(c[3]) * 100;
}
var canvas = document.createElement("canvas")
canvas.width = img.width;
canvas.height = img.height;
var context = canvas.getContext("2d");
context.putImageData( img, 0, 0 );
img.canvas = canvas;
return canvas;
}
p.image = function image( img, x, y, w, h ) {
x = x || 0;
y = y || 0;
var obj = getImage(img);
if ( curTint >= 0 ) {
var oldAlpha = curContext.globalAlpha;
curContext.globalAlpha = curTint / opacityRange;
}
if ( arguments.length == 3 ) {
curContext.drawImage( obj, x, y );
} else {
curContext.drawImage( obj, x, y, w, h );
}
if ( curTint >= 0 ) {
curContext.globalAlpha = oldAlpha;
}
if ( img._mask ) {
var oldComposite = curContext.globalCompositeOperation;
curContext.globalCompositeOperation = "darker";
p.image( img._mask, x, y );
curContext.globalCompositeOperation = oldComposite;
}
};
p.exit = function exit() {
clearInterval(looping);
};
p.save = function save( file ){};
p.loadImage = function loadImage( file ) {
var img = document.getElementById(file);
if ( !img )
return;
var h = img.height, w = img.width;
var canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
var context = canvas.getContext("2d");
context.drawImage( img, 0, 0 );
var data = buildImageObject( context.getImageData( 0, 0, w, h ) );
data.img = img;
return data;
};
p.loadFont = function loadFont( name ) {
if(name.indexOf(".svg")==-1){
return {
name: name,
width: function( str ) {
if ( curContext.mozMeasureText )
return curContext.mozMeasureText( typeof str == "number" ?
String.fromCharCode( str ) :
str) / curTextSize;
else
return 0;
}
};
}else{// If the font is a glyph, calculate by SVG table
var font=p.loadGlyphs(name);
return {
name: name,
glyph: true,
units_per_em: font.units_per_em,
horiz_adv_x: 1/font.units_per_em*font.horiz_adv_x,
ascent: font.ascent,
descent: font.descent,
width: function( str ) {
var width=0;
var len = str.length;
for(var i=0;i < len;i++){
try{width+=parseFloat(p.glyphLook(p.glyphTable[name],str[i]).horiz_adv_x);}
catch(e){;}
}
return width/p.glyphTable[name].units_per_em;
}
}
}
};
p.textFont = function textFont( name, size ) {
curTextFont = name;
p.textSize( size );
};
p.textSize = function textSize( size ) {
if ( size ) {
curTextSize = size;
}
};
p.textAlign = function textAlign(){};
p.glyphLook = function glyphLook(font,chr){
try{
switch(chr){
case "1":return font["one"];break;
case "2":return font["two"];break;
case "3":return font["three"];break;
case "4":return font["four"];break;
case "5":return font["five"];break;
case "6":return font["six"];break;
case "7":return font["seven"];break;
case "8":return font["eight"];break;
case "9":return font["nine"];break;
case "0":return font["zero"];break;
case " ":return font["space"];break;
case "$":return font["dollar"];break;
case "!":return font["exclam"];break;
case '"':return font["quotedbl"];break;
case "#":return font["numbersign"];break;
case "%":return font["percent"];break;
case "&":return font["ampersand"];break;
case "'":return font["quotesingle"];break;
case "(":return font["parenleft"];break;
case ")":return font["parenright"];break;
case "*":return font["asterisk"];break;
case "+":return font["plus"];break;
case ",":return font["comma"];break;
case "-":return font["hyphen"];break;
case ".":return font["period"];break;
case "/":return font["slash"];break;
case "_":return font["underscore"];break;
case ":":return font["colon"];break;
case ";":return font["semicolon"];break;
case "<":return font["less"];break;
case "=":return font["equal"];break;
case ">":return font["greater"];break;
case "?":return font["question"];break;
case "@":return font["at"];break;
case "[":return font["bracketleft"];break;
case "\\":return font["backslash"];break;
case "]":return font["bracketright"];break;
case "^":return font["asciicircum"];break;
case "`":return font["grave"];break;
case "{":return font["braceleft"];break;
case "|":return font["bar"];break;
case "}":return font["braceright"];break;
case "~":return font["asciitilde"];break;
default:return font[chr]; break;
}
}catch(e){;}
}
p.text = function text( str, x, y ) {
if(!curTextFont.glyph){
if ( str && curContext.mozDrawText ) {
curContext.save();
curContext.mozTextStyle = curTextSize + "px " + curTextFont.name;
curContext.translate(x, y);
curContext.mozDrawText( typeof str == "number" ?
String.fromCharCode( str ) :
str );
curContext.restore();
}
}else{
var font=p.glyphTable[curTextFont.name];
curContext.save();
curContext.translate(x,y+curTextSize);
var upem = font["units_per_em"];
var newScale=1/upem*curTextSize;
curContext.scale(newScale,newScale);
var len = str.length;
for(var i=0;i < len;i++){
try{p.glyphLook(font,str[i]).draw();}
catch(e){;}
}
curContext.restore();
}
};
// Load Batik SVG Fonts and parse to pre-def objects for quick rendering - F1LT3R
p.loadGlyphs=function loadGlyph(url){
// SJAX SVG as XML D.O.
var loadXML=function loadXML(){
try{var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");}
catch(e){try{xmlDoc=document.implementation.createDocument("","",null);}
catch(e){p.println(e.message);return;}}
try{// Firefox, Mozilla, Opera, etc.
xmlDoc.async=false;
xmlDoc.load(url);
parse(xmlDoc.getElementsByTagName("svg")[0]);
}
catch(e){try{// Google Chrome, Safari etc.
try{console.log(e)}catch(e){alert(e);}
var xmlhttp = new window.XMLHttpRequest();
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
parse(xmlhttp.responseXML.documentElement);
}catch(e){}
}
}
// Return arrays of SVG commands and coords
var regex=function regex(needle,hay){
var regexp=new RegExp(needle,"g");
var i=0;
var results=[];
while(results[i]=regexp.exec(hay)){i++;}
return results;
}
// Parse SVG font-file
var parse=function parse(svg){
// Store font attributes
var font=svg.getElementsByTagName("font");
p.glyphTable[url]["horiz_adv_x"]=font[0].getAttribute("horiz-adv-x");
var font_face=svg.getElementsByTagName("font-face")[0];
p.glyphTable[url]["units_per_em"]=parseFloat(font_face.getAttribute("units-per-em"));
p.glyphTable[url]["ascent"]=parseFloat(font_face.getAttribute("ascent"));
p.glyphTable[url]["descent"]=parseFloat(font_face.getAttribute("descent"));
var getXY = "[0-9\-]+";
var glyph = svg.getElementsByTagName("glyph");
// Loop through each glyph in the SVG
var len = glyph.length;
for(var i=0;i < len;i++){
// Store attributes for this glyph
var unicode = glyph[i].getAttribute("unicode");
var name = glyph[i].getAttribute("glyph-name");
var horiz_adv_x = glyph[i].getAttribute("horiz-adv-x");
if(horiz_adv_x==null){var horiz_adv_x=p.glyphTable[url]['horiz_adv_x'];}
var buildPath = function buildPath(d){
var c = regex("[A-Za-z][0-9\- ]+|Z",d);
// Begin storing path object
var path="var path={draw:function(){curContext.beginPath();curContext.save();";//curContext.beginPath();
// Loop through SVG commands translating to canvas eqivs functions in path object
var x=0,y=0,cx=0,cy=0,nx=0,ny=0,d=0,a=0,lastCom="";
var lenC = c.length-1;
for(var j=0;j < lenC;j++){
var com=c[j][0];
var xy=regex(getXY,com);
switch(com[0]){
case "M"://curContext.moveTo(x,-y);
x=parseFloat( xy[0][0] );
y=parseFloat( xy[1][0] );
path+="curContext.moveTo("+(x)+","+(-y)+");";
break;
case "L"://curContext.lineTo(x,-y);
x=parseFloat( xy[0][0] );
y=parseFloat( xy[1][0] );
path+="curContext.lineTo("+(x)+","+(-y)+");";
break;
case "H"://curContext.lineTo(x,-y)
x=parseFloat( xy[0][0] );
path+="curContext.lineTo("+(x)+","+(-y)+");";
break;
case "V"://curContext.lineTo(x,-y);
y=parseFloat( xy[0][0] );
path+="curContext.lineTo("+(x)+","+(-y)+");";
break;
case "T"://curContext.quadraticCurveTo(cx,-cy,nx,-ny);
nx=parseFloat( xy[0][0] );
ny=parseFloat( xy[1][0] );
if(lastCom=="Q"||lastCom=="T"){
d=Math.sqrt(Math.pow(x-cx,2)+Math.pow(cy-y,2));
a=Math.PI+Math.atan2(cx-x,cy-y);
cx=x+(Math.sin(a)*(d));
cy=y+(Math.cos(a)*(d));
}else{cx=x;cy=y;}
path+="curContext.quadraticCurveTo("+(cx)+","+(-cy)+","+(nx)+","+(-ny)+");";
x=nx;y=ny;
break;
case "Q"://curContext.quadraticCurveTo(cx,-cy,nx,-ny);
cx=parseFloat( xy[0][0] );
cy=parseFloat( xy[1][0] );
nx=parseFloat( xy[2][0] );
ny=parseFloat( xy[3][0] );
path+="curContext.quadraticCurveTo("+(cx)+","+(-cy)+","+(nx)+","+(-ny)+");";
x=nx;y=ny;
break;
case "Z"://curContext.closePath();
path+="curContext.closePath();";
break;
}
lastCom=com[0];
}
path+="doStroke?curContext.stroke():0;";
path+="doFill?curContext.fill():0;";
path+="curContext.restore();";
path+="curContext.translate("+(horiz_adv_x)+",0);";
path+="}}";
return path;
}
// Split path commands in glpyh
var d=glyph[i].getAttribute("d");
if(d!==undefined){
var path=buildPath(d);
eval(path);
// Store glyph data to table object
p.glyphTable[url][name]={
name:name,
unicode:unicode,
horiz_adv_x:horiz_adv_x,
draw:path.draw
}
}
} // finished adding glyphs to table
}
// Create a new object in glyphTable to store this font
p.glyphTable[url]={};
// Begin loading the Batik SVG font...
loadXML(url);
// Return the loaded font for attribute grabbing
return p.glyphTable[url];
}
// Returns a line to lnPrinted() for user handling
p.lnPrinted = function lnPrinted(){};
p.printed = function printed(){};
p.println = function println(){
var Caller = arguments.callee.caller.name.toString();
if ( arguments.length > 1 ) {
Caller!="print"?
p.ln = arguments:
p.ln = arguments[0];
} else {
p.ln = arguments[0];
}
Caller=="print"?
p.printed(arguments):
p.lnPrinted();
};
p.print = function print(){ p.println(arguments[0])};
p.char = function char( key ) {
return key;
};
p.map = function map( value, istart, istop, ostart, ostop ) {
return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
};
String.prototype.replaceAll = function(re, replace) {
return this.replace(new RegExp(re, "g"), replace);
};
p.Point = function Point( x, y ) {
this.x = x;
this.y = y;
this.copy = function() {
return new Point( x, y );
}
};
p.Random = function() {
var haveNextNextGaussian = false;
var nextNextGaussian;
this.nextGaussian = function() {
if (haveNextNextGaussian) {
haveNextNextGaussian = false;
return nextNextGaussian;