diff --git a/js/anchor.js b/js/anchor.js index 0744810..e1723df 100644 --- a/js/anchor.js +++ b/js/anchor.js @@ -212,6 +212,36 @@ Anchor.prototype.normalizeRotate = function() { this.rotate.y = utils.modulo( this.rotate.y, TAU ); this.rotate.z = utils.modulo( this.rotate.z, TAU ); }; + +Anchor.prototype.toJSON = function () { + var result = {}; + var optionKeys = this.constructor.optionKeys; + + [...optionKeys, 'children'].forEach(function (key) { + if (['addTo', 'dragRotate', 'element', 'resize'].includes(key)) return; + var value = this[key]; + var defaults = this.constructor.defaults; + + if (!['undefined', 'function'].includes(typeof value) && value !== defaults[key]) { + if (Array.isArray(value) && value.length === 0) { + return; + } + if (value.toJSON) { + var serialized = value.toJSON(); + if (typeof serialized !== 'undefined') { + if (key === 'scale' && serialized === 1) { + return; + } + result[key] = serialized; + } + } else { + result[key] = value; + } + } + }, this); + + return result; +}; // ----- subclass ----- // diff --git a/js/vector.js b/js/vector.js index b896526..aa120d4 100644 --- a/js/vector.js +++ b/js/vector.js @@ -148,6 +148,28 @@ Vector.prototype.magnitude2d = function() { Vector.prototype.copy = function() { return new Vector( this ); }; + +Vector.prototype.toJSON = function() { + var x = this.x; + var y = this.y; + var z = this.z; + + if ( x === y && y === z ) { + return ( x !== 0 ) ? x : undefined; + } + + var obj = { x: x, y: y, z: z }; + var result = {}; + + Object.keys( obj ).forEach( function ( key ) { + var value = obj[ key ]; + if ( value !== 0 ) { + result[ key ] = value; + } + }) + + return Object.keys( result ).length ? result : undefined; +}; return Vector;