2
0

Style.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /**
  2. * Style represents in a generic way a style applied to canvas drawing.
  3. *
  4. * Some styles (e.g. gradients, patterns) required a context to be generated this provides a generic way to share styles between objects.
  5. *
  6. * @class
  7. */
  8. function Style()
  9. {
  10. /**
  11. * Cached style object pre-generated from previous calls. To avoid regenerating the same style object every cycle.
  12. *
  13. * Inherited classes should write their own get method that returns the style object and stores it in this property.
  14. *
  15. * @type {string | CanvasGradient | CanvasPattern}
  16. */
  17. this.cache = null;
  18. /**
  19. * Indicates if the style object needs to be updated, should be used after applying changed to the style in order to generate a new object.
  20. *
  21. * Inherited classes should implement this functionality.
  22. *
  23. * @type {boolean}
  24. */
  25. this.needsUpdate = true;
  26. }
  27. /**
  28. * Get generated style object from style data and the drawing context.
  29. *
  30. * @param {CanvasRenderingContext2D} context Context being used to draw the object.
  31. * @return {string | CanvasGradient | CanvasPattern} Return the canvas style object generated.
  32. */
  33. Style.prototype.get = function(context) {};
  34. /**
  35. * Serialize the style to JSON object, called by the objects using these styles.
  36. *
  37. * @return {Object} Serialized style data.
  38. */
  39. Style.prototype.serialize = function() {};
  40. /**
  41. * Parse the style attributes from JSON object data created with the serialize() method.
  42. *
  43. * @param {Object} data Serialized style data.
  44. */
  45. Style.prototype.parse = function(data) {};
  46. /**
  47. * List of available style types known by the application. Stores the object constructor by object type.
  48. *
  49. * @static
  50. * @type {Map<string, Function>}
  51. */
  52. Style.types = new Map([]);
  53. /**
  54. * Register a style type to be serializable. Associates the type string to the object constructor.
  55. *
  56. * @param {Function} constructor Style constructor.
  57. * @param {string} type Style type name.
  58. */
  59. Style.register = function(constructor, type)
  60. {
  61. Style.types.set(type, constructor);
  62. };
  63. /**
  64. * Parse style from JSON serialized data, created a style of the correct data type automatically and parses its data.
  65. *
  66. * @param data JSON serialized data.
  67. * @returns {Style} Parsed style from the provided data.
  68. */
  69. Style.parse = function (data)
  70. {
  71. var style = new (Style.types.get(data.type))();
  72. style.parse(data);
  73. return style;
  74. };
  75. export {Style};