raphael.json.js 1006 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * Licensed under the MIT license:
  3. * http://www.opensource.org/licenses/mit-license.php
  4. *
  5. */
  6. (function() {
  7. Raphael.fn.toJSON = function(callback) {
  8. var
  9. data,
  10. elements = new Array,
  11. paper = this
  12. ;
  13. for ( var el = paper.bottom; el != null; el = el.next ) {
  14. data = callback ? callback(el, new Object) : new Object;
  15. if ( data ) elements.push({
  16. data: data,
  17. type: el.type,
  18. attrs: el.attrs,
  19. transform: el.matrix.toTransformString(),
  20. id: el.id
  21. });
  22. }
  23. return JSON.stringify(elements);
  24. }
  25. Raphael.fn.fromJSON = function(json, callback) {
  26. var
  27. el,
  28. paper = this
  29. ;
  30. if ( typeof json === 'string' ) {
  31. json = JSON.parse(json);
  32. }
  33. for ( var i in json ) {
  34. if ( json.hasOwnProperty(i) ) {
  35. el = paper[json[i].type]()
  36. .attr(json[i].attrs)
  37. .transform(json[i].transform);
  38. el.id = json[i].id;
  39. if ( callback ) el = callback(el, json[i].data);
  40. if ( el ) paper.set().push(el);
  41. }
  42. }
  43. }
  44. })();