/
canvasengine.js
6828 lines (5701 loc) · 175 KB
/
canvasengine.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
/*
Copyright (C) 2012 by WebCreative5 - Samuel Ronce
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// Erik Möller
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
// --
if (typeof Element != "undefined") {
var prop, vendors = ['ms', 'moz', 'webkit', 'o', 'khtml'];
for(var x = 0; x < vendors.length && !Element.prototype.requestFullScreen; ++x) {
Element.prototype.requestFullScreen = Element.prototype[vendors[x]+'RequestFullScreen'];
document.cancelFullScreen = document[vendors[x]+'CancelFullScreen'];
}
}
Class.create("ModelClientClass", {
create: function(name, events, model) {
if (!(events instanceof Array)) {
model = events;
events = false;
}
model.events = events;
Class.create(name, model);
},
"new": function(name) {
var _class = Class["new"](name).extend({
_methods: {},
emit: function(name, data, callback) {
if (!data) {
data = [];
}
if (typeof data == "function") {
callback = data;
}
if (callback) {
this.on(name, callback);
}
if (this[name]) {
if (!(data instanceof Array)) {
var new_a = [];
for (var key in data) {
new_a.push(data[key]);
}
data = new_a;
}
var ret = this[name].apply(this, data);
this.call(name, ret);
}
},
on: function(name, callback) {
if (!this._methods[name]) {
this._methods[name] = {};
}
this._methods[name].callback = callback;
},
call: function(name, data) {
if (this._methods[name]) this._methods[name].callback(data);
}
});
if (this.events) {
for (var key in this.events) {
obj = _class[events[key]];
if (obj) {
obj.on(this.events[key], function(data) {
if (!data) {
data = {};
}
obj.call(_class, data);
});
}
}
}
return _class;
}
});
var Model = Class["new"]("ModelClientClass"),
Global_CE;
/**
@doc server/
@property io `(>= 1.3.0)` Object of Socket.io. View [https://github.com/LearnBoost/socket.io/wiki/Exposed-events#client](https://github.com/LearnBoost/socket.io/wiki/Exposed-events#client)
@type Object
@default null
@example
CE.connectServer('http://127.0.0.1', 8333);
CE.io.emit("Foo", {bar: "test"});
*/
CanvasEngine.io = null;
CanvasEngine.socketIO = function() {
if (typeof(io) == "undefined") {
throw "Please add socket.io - http://socket.io";
}
return io;
};
// TODO
CanvasEngine.User = {
autoAuthentication: function(cookie_name, params) {
CanvasEngine.socketIO();
if (typeof cookie_name != "string") {
params = cookie_name;
cookie_name = "canvasengine";
}
var regexp = new RegExp(cookie_name + "=(\{.*?\})" ,"i"),
match = document.cookie.match(regexp), data;
if (match && match[1]) {
try {
data = JSON.parse(match[1]);
setTimeout(function() {
CanvasEngine.io.emit("_autoAuthentication", {
session: data.session_id
});
}, 200);
CanvasEngine.io.on("_autoAuthentication", function(ret) {
if (ret.ret == "success" && params.success) {
params.success(ret.data_empty);
}
else if (ret.ret == "failed" && params.failed) {
params.failed(ret.err);
}
});
}
catch (e) {
console.warn("Error session format in cookie ; ", e.stack);
}
}
},
_setCookie: function(name, val) {
var del = val == undefined;
name = name || "canvasengine";
var date = new Date();
date.setTime(date.getTime() + ((del ? -1 : 2) *24*60*60*1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = name + '=' + (del ? "" : JSON.stringify(val)) + expires + '; path=/';
},
authentication: function(username, password, params) {
var self = this;
CanvasEngine.socketIO();
CanvasEngine.io.emit("_authentication", {
username: username,
password: password
});
CanvasEngine.io.on("_authentication", function(ret) {
if (ret.ret == "success" && params.success) {
self._setCookie(params.cookie_name, {session_id: ret.session_id });
params.success(ret.data_empty);
}
else if (ret.ret == "failed" && params.failed) {
params.failed(ret.err);
}
});
},
register: function(username, password, params) {
CanvasEngine.socketIO();
CanvasEngine.io.emit("_register", {
username: username,
password: password,
data: params.data
});
CanvasEngine.io.on("_register", function(ret) {
if (ret.ret == "success" && params.success) {
params.success();
}
else if (ret.ret == "failed" && params.failed) {
params.failed(ret.err);
}
});
},
logout: function(params) {
params = params || {};
var self = this;
CanvasEngine.socketIO();
CanvasEngine.io.emit("_logout");
this._setCookie(params.cookie_name);
},
isLogged: function() {
}
};
/**
@doc server/
@method connectServer `(>= 1.3.0)` Allows you to connect to the server. Created a Socket object from socket.io. Use the property `io` then to perform methods of Socket.io
To use Socket.io , do not forget to put the JS file :
<script src="socket.io.min.js"></script>
@static
@param {String} host IP or host name
@param {Integer} port Port
@return CanvasEngineClass
@example
CE.connectServer('http://127.0.0.1', 8333);
CE.io.on("reconnecting", function() {
console.log("reconnecting");
});
*/
CanvasEngine.connectServer = function(host, port) {
CanvasEngine.socketIO();
CanvasEngine.io = io.connect(host + ":" + port);
};
/**
@class CanvasEngine
@static
@details
See "defines" method
*/
/**
@doc engine/
@method defines Initialize CanvasEngine by setting the canvas. Note two ways to declare a canvas in HTML :
1. <canvas>
<canvas id="canvas_id" width="640" height="480"></canvas>
2. <div>
<div id="canvas_id" width="640" height="480"></div>
In case you use the div tag to add a layer of DOM elements is possible. For example, to add forms.
In `ready` method, you can use jQuery (Do not forget to include the library in the header before) :
var el = $('<div>');
stage.append(el);
> Valid for version >= 1.3.1
@static
@param {String} canvas canvas ID
@param {Object} params (optional) additional parameters
* swf_sound : see Sound class (obsolete, use `soundmanager` object)
* soundmanager : `(>= 1.2.7)` SoundManager options [http://www.schillmania.com/projects/soundmanager2/doc/#sm-config](http://www.schillmania.com/projects/soundmanager2/doc/#sm-config)
Example :
{url: "swf/", debugMode: false}
* cocoonjs : Object indicating the size of the canvas. Use this property if you want to compile your project with CocoonJS ([http://ludei.com](http://ludei.com))
Example :
{width: 640, height: 480}
* render : Do not rendering (true by default)
* contextmenu `(>= 1.2.6)` : Show right-click menu (false by default)
* ignoreLoadError `(>= 1.2.7)` : Begins the scene even if the materials are not loaded
Example :
var canvas = CE.defines("canvas_id", {
ignoreLoadError: true
}).
ready(function() {
canvas.Scene.call("MyScene");
});
canvas.Scene.New({
name: "MyScene",
materials: {
images: {
foo: "path/picture.png" // picture.png does not exist but ...
}
},
ready: function(stage) { // ready() is still called
var el = this.createElement();
el.drawImage("foo"); // image is ignored
stage.append(el);
}
});
@return CanvasEngineClass
@example
"CE" is equivalent to "CanvasEngine"
var canvas = CE.defines("canvas_id").
ready(function() {
// DOM is ready
});
View `ready` method
*/
CanvasEngine.defines = function(canvas, params) {
params = params || {};
if (params.render === undefined) params.render = true;
if (typeof canvas == "string") {
canvas = [canvas];
}
var CanvasEngine;
/**
@doc engine
@class CanvasEngineClass Main class to use Canvas Engine
var canvas = CE.defines("canvas_id"); // CanvasEngine object
canvas.ready(function(ctx) {
canvas.Scene.call("MyScene");
});
*/
Class.create("CanvasEngineClass", {
_noConflict: false,
initialize: function(element) {
this.canvas = canvas;
this.el_canvas = [];
},
/**
@doc engine/
@method ready Calls the function when DOM is ready. The method uses "window.load" or SoundManager callback if it is present. If the DOM is already loaded (with jquery by example). Do not put the callback function
@param {Function} callback
@return CanvasEngineClass
@example
var canvas = CE.defines("canvas_id").
ready(function() {
// DOM is ready
});
With jQuery :
$(function() {
var canvas = CE.defines("canvas_id").ready();
});
*/
ready: function(callback) {
var self = this;
CanvasEngine.Sound._manager = typeof(soundManager) !== "undefined";
if (CanvasEngine.Sound._manager) {
soundManager.setup(_CanvasEngine.extend({
// swf_sound : obsolete
url: params.swf_sound ? params.swf_sound : "swf/",
onready: onReady
}, params.soundmanager));
}
else if (!callback) {
onReady();
}
else {
window.onload = onReady;
}
function onReady() {
for (var i=0 ; i < self.canvas.length ; i++) {
self.el_canvas.push(self.Canvas["new"](self.canvas[i]));
}
if (params.render) CanvasEngine.Scene._loop(self.el_canvas);
if (callback) callback();
}
return this;
},
plugins: function() {
},
mouseover: false,
noConflict: function() {
this._noConflict = true;
},
/**
@doc materials
@class Materials Resource management game. The class is used with the properties "materials" in the scene but you can still use it for loading external resources to the scene
@example
Using Sound :
var canvas = CE.defines("canvas_id").
ready(function() {
canvas.Scene.call("MyScene");
});
canvas.Scene.new({
name: "MyScene",
ready: function(stage) {
canvas.Materials.load("images", [
{img1: "path/to/img1.png"},
{img2: "path/to/im2.png"}
], function(img) {
console.log("Image is loaded");
}, function() {
console.log("All images are loaded");
});
}
});
*/
Materials: {
images: {},
_buffer: {},
_cache_canvas: {},
sounds: {},
videos: {},
fonts: {},
data: {},
/**
@doc materials/
@method get Get the picture or sound according to its identifier
@param {String} id
@param {String} type (optional) If two identical identifier is several types, specify the type: "image" or "sound"
@return {HTML5Audio|Image}
*/
get: function(id, type) {
if (type) {
return this[type + "s"][id];
}
if (_m = this.images[id] || this.sounds[id] || this.videos[id] || this.data[id]) {
return _m
}
else if (id instanceof Image ||
id instanceof HTMLCanvasElement ||
id instanceof HTMLVideoElement ||
id instanceof HTMLAudioElement) {
return id;
}
if (params.ignoreLoadError) {
return false;
}
throw "Cannot to get the data \"" + id + "\" because it does not exist";
},
setLang: function(id, path, callback) {
if (typeof(Languages) == "undefined") {
console.warn("Languages script doesn't exist. See https://github.com/RSamaium/Languages");
if (callback) callback();
return this;
}
var self = this;
if (this.data["languages_" + id]) {
callback();
return this;
}
Languages.init(id, path, function() {
self.data["languages_" + this.current] = this;
callback();
});
return this;
},
/**
@doc materials/
@method imageToCanvas Converts an image (Image) in Canvas. The returned object is :
{
canvas: {HTML5CanvasElement},
ctx: {Context2d}
}
@param {String} id Image id
@param {Boolean} cache Image id
@return {Object}
*/
imageToCanvas: function(id, params) {
params = params || {};
if (this._cache_canvas[id] && params.cache) {
return this._cache_canvas[id];
}
var img = this.get(id), canvas, ctx;
if (!img) return;
var w = params.width || img.width,
h = params.height || img.height,
canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, w, h);
this._cache_canvas[id] = {
canvas: canvas,
ctx: ctx
};
return this._cache_canvas[id];
},
createBuffer: function(real_id) {
var id = "_opaque_" + real_id;
var video = this.get(real_id, "video") || real_id instanceof HTMLVideoElement;
if (video) {
return video;
}
if (!this._buffer[id]) {
this._buffer[id] = this.opaqueImage(real_id);
}
return this._buffer[id];
},
/**
@doc materials/
@method transparentColor Make a color transparent in the image
@param {String} id Image id
@param {String} color hexadecimal code
@param {Boolean} cache (optional) Puts the canvas generated in cache (false by default)
@return {HTML5Canvas}
*/
transparentColor: function(id, color, cache) {
var imageData, data, rgb,
_canvas = this.imageToCanvas(id, {
cache: cache
}),
canvas = _canvas.canvas,
ctx = _canvas.ctx;
imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
data = imageData.data;
rgb = _CanvasEngine.hexaToRGB(color);
for(var i = 0, n = data.length; i < n; i += 4) {
var red = data[i];
var green = data[i + 1];
var blue = data[i + 2];
if (red == rgb[0] && green == rgb[1] && blue == rgb[2]) {
data[i + 3] = 0;
}
}
ctx.putImageData(imageData, 0, 0);
return canvas;
},
/**
@doc materials/
// @method invertColor Inverts the colors of the image
@param {String} id Image id
@param {Boolean} cache (optional) Puts the canvas generated in cache (false by default)
@return {HTML5Canvas}
*/
invertColor: function(id, cache) {
var imageData, data,
_canvas = this.imageToCanvas(id),
canvas = _canvas.canvas,
ctx = _canvas.ctx;
imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
data = imageData.data;
for(var i = 0; i < data.length; i += 4) {
data[i] = 255 - data[i];
data[i + 1] = 255 - data[i + 1];
data[i + 2] = 255 - data[i + 2];
}
ctx.putImageData(imageData, 0, 0);
return canvas;
},
/**
@doc materials/
@method cropImage Can crop an image to use independently. Useful for creating patterns in HTML5
@param {String} id Image id
@param {Integer} x Position X
@param {Integer} y Position Y
@param {Integer} w Width
@param {Integer} h height
@return {HTML5Canvas}
*/
cropImage: function(id, x, y, w, h) {
var imageData, data, rgb,
_canvas = this.imageToCanvas(id);
if (!_canvas) {
return;
}
var canvas = _canvas.canvas,
ctx = _canvas.ctx
imageData = ctx.getImageData(x, y, w, h);
canvas.width = w;
canvas.height = h;
ctx.putImageData(imageData, 0, 0);
return canvas;
},
/**
@doc materials/
@method opaqueImage Makes transparent pixels (> 0 and < 255) opaque
@param {String} id Image id
@return {HTML5Canvas}
*/
opaqueImage: function(id) {
var _canvas = this.imageToCanvas(id),
canvas = _canvas.canvas,
ctx = _canvas.ctx;
imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
if (data[i+3] > 0) {
data[i+3] = 255;
}
}
ctx.putImageData(imageData, 0, 0);
return canvas;
},
// TODO Nearest-neighbor
/**
@doc materials/
@method getExtension Gets the file extension
@param {String} filename File name
@return {String}
*/
getExtension: function(filename) {
return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename)[0] : undefined;
},
/**
@doc materials/
@method getBasePath Retrieves the base of a path
@param {String} path Path
@param {Boolean} (optional) slash If there is a non-empty path and the parameter is true then a slash is added to the end of the string returned
@return {String}
@example
canvas.Materials.getBasePath("sound/sample.mp3"); // return "sound"
*/
getBasePath: function(path, slash) {
var p = path.substring(0, path.lastIndexOf('/'))
return p != "" && slash ? p + "/" : p;
},
/**
@doc materials/
@method getFilename Gets the file name with or without the extension in a path
@param {String} path Path
@param {Boolean} ext (optional) Show extension if true (false by default)
@return {String}
@example
canvas.Materials.getFilename("sound/sample.mp3"); // return "sample"
*/
getFilename: function(path, ext) {
var parts = path.replace(/^.*[\\\/]/, '');
if (!ext) {
parts = parts.split('.');
}
else {
return parts;
}
return parts.slice(0, parts.length - 1).join(".");
},
Transition: {
_data: {},
set: function(id, data) {
var imageData, _data, new_data = [];
if (this._data[id]) {
return this._data[id];
}
if (!(id instanceof Array)) {
var _canvas = CanvasEngine.Materials.imageToCanvas(id, {
width: 1024,
height: 768
});
if (typeof Uint8ClampedArray != "undefined") {
new_data = new Uint8ClampedArray(_canvas.canvas.width * _canvas.canvas.height);
}
imageData = _canvas.ctx.getImageData(0, 0, _canvas.canvas.width, _canvas.canvas.height);
_data = imageData.data;
var j=0;
for (var i=0; i < _data.length; i+=4) {
new_data[j] = _data[i];
j++;
}
}
else {
new_data = data;
}
this._data[id] = new_data;
return new_data;
},
get: function(id) {
return this._data[id];
}
},
/**
@doc materials/
@method load Load a resource
@param {String} type
* images : Loading images.
images: {
{foo: "bar.png"}
}
For use :
el.drawImage("foo"); // el is an element
It is possible to define a transparent color to make the image with `transparentcolor` option:
images: {
{foo: {path: "bar.png", transparentcolor: "#ff0000"}
}
You can set the image as a scene transition :
images: {
{foo: {path: "bar.png", transition: true}
}
* sounds : Loading sound. Test if the browser supports the sound. If your browser does not support the format, it will take another file with the same name but with a different extension
sounds: {
foo: "bar.mp3"
}
On Firefox, it will automatically search `bar.ogg`
For use :
canvas.Sound.get("foo").play(); // "canvas" is namespace
* videos : add videos which will be displayed in the canvas :
videos: {
foo: "bar.mp4"
}
To use :
el.drawImage("foo"); // el is an element
To use video API :
var video = canvas.Materials.get("foo", "video");
video.play();
To use the webcam :
videos: {
foo: {webcam: {audio: false, video: true}}
}
To display and manipulate is the same as the single video
* fonts
For Internet Explorer, it will take a file with the same name but with the extension `.eot`
fonts: {
foo: "bar.ttf"
}
For use are in the text:
el.font = 'normal 40pt foo'; // "el" is an element
For fonts, you can use [Web Font Loader](https://github.com/typekit/webfontloader)
fonts: {
google: { families: ["test"] },
foo: "bar.ttf"
}
For use are in the text:
el.font = 'normal 40pt test';
You can find fonts from [Google Fonts](http://www.google.com/fonts) and other modules (see [Web Font Loader Github](https://github.com/typekit/webfontloader))
* data : Loading a JSON file
data: {
foo: "bar.json"
}
@param {Array|Object} path Paths to resources.
* If array : Elements are composed of objects where the key is the identifier and value is the path
[
{img1: "path/to/img1.png"},
{img2: "path/to/im2.png"}
]
* If object, the key is the identifier and value is the path :
{img1: "path/to/img1.png", img2: "path/to/im2.png"}
The value can be an object to give several parameters :
{img1: {path: "path/to/img1.png", transparentcolor: "#ff0000"}, img2: "path/to/im2.png"}
`path` is the path and "transparentcolor" the color that will be transparent image
By default, the order is done alphabetically. But since version 1.3.2, you can choosethe order of loading. Here, the `img2` image forced to load first
{img2: {path: "path/to/img1.png", index: 0}, img1: "path/to/im2.png", index: 1}
So use `index` to define an order. The smaller will be loaded first. The index starts at 0 (order of an array)
@param {Function} onLoad (optional) Callback when a resource is loaded
Two parameters are returned :
1. {Image|Sound|Video|Font|JSON} The element loaded
2. {Object} : The information of the resource (path, index, etc.)
@param {Function} onFinish (optional) Callback when all resources are loaded
*/
load: function(type, path, onLoad, onFinish) {
var i=0, p, self = this, materials = [], img_data;
if (!(path instanceof Array)) {
path = [path]
}
for (var j=0 ; j < path.length ; j++) {
p = path[j];
if (p.id) {
materials.push(p);
}
else {
for (var key in p) {
img_data = {};
img_data = _CanvasEngine.extend({}, p[key]);
if (typeof p[key] == "string") {
img_data.path = p[key];
}
if (img_data.id) {
img_data._id = img_data.id;
}
img_data.id = key;
materials.push(img_data);
if (img_data.index != undefined) {
_CanvasEngine.moveArray(materials, materials.length-1, img_data.index);
}
}
}
}
switch (type) {
case "images":
load();
break;
case "sounds":
loadSounds();
break;
case "fonts":
loadFont();
break;
case "videos":
loadVideos();
break;
case "data":
loadData();
break;
}
function load() {
var img;
if (materials[i]) {
img = new Image();
img.onload = function() {
var _img;
if (materials[i].transparentcolor) {
_img = self.transparentColor(img, materials[i].transparentcolor);
}
if (materials[i].invertcolor) {
_img = self.invertColor(img);
}
else {
_img = img;
}
self.images[materials[i].id] = _img;
if (materials[i].transition) {
self.Transition.set(materials[i].id);
}
if(onLoad) onLoad.call(self, _img, materials[i]);
i++;
load();
};
img.onerror = function(e) {
if (params.ignoreLoadError) {
if (onLoad) onLoad.call(self, e);
i++;
load();
}
}
img.src = materials[i].path;
}
else {
if (onFinish) onFinish.call(self);
}
}