forked from AliasIO/Raphael.JSON
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathraphael.json.js
66 lines (56 loc) · 1.38 KB
/
raphael.json.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
/*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
*/
(function() {
Raphael.fn.toJSON = function(callback) {
var
data,
elements = new Array,
paper = this
;
for ( var el = paper.bottom; el != null; el = el.next ) {
data = callback ? callback(el, new Object) : new Object;
if ( data ) elements.push({
data: data,
type: el.type,
attrs: el.attrs,
transform: el.matrix.toTransformString(),
id: el.id
});
}
var cache = [];
var o = JSON.stringify(elements, function (key, value) {
//http://stackoverflow.com/a/11616993/400048
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
});
cache = null;
return o;
}
Raphael.fn.fromJSON = function(json, callback) {
var
el,
paper = this
;
if ( typeof json === 'string' ) json = JSON.parse(json);
for ( var i in json ) {
if ( json.hasOwnProperty(i) ) {
el = paper[json[i].type]()
.attr(json[i].attrs)
.transform(json[i].transform);
el.id = json[i].id;
if ( callback ) el = callback(el, json[i].data);
if ( el ) paper.set().push(el);
}
}
}
})();