I have a canvas object that I can call it that
var canvas = new Canvas();
The canvas object also has many features in its prototype. An object essentially creates a canvas element with several functions, such as setWidth , getContext , etc.
I also have a Layer object, which is essentially a canvas with added functionality. I thought it would be nice to install a Layer prototype for Canvas . It worked great and everything was fine.
The problem starts when I want to use several layers, since each layer should have its own canvas. But since the canvas is a Layers prototype, the prototype points to only one canvas element. Therefore, when I start using multiple layers, canvases are always overwritten, since the canvas element in layer prototypes points to the same canvas object.
Hope so far I made sense!
I know that I could add canvas to the layer as a property, but instead
layer.setWidth(900);
I would have to do
layer.canvas.setWidth(900);
I assume my question is how can I inherit the functions of Canvas objects, but when creating a new layer, create it using the new canvas element?
As per code request (simplified)
var carl = {}; carl.Canvas = (function() { "use strict"; function Canvas(config) { this._init(config); }; Canvas.prototype._init = function(config) { this.element = document.createElement("canvas"); this.context = this.element.getContext("2d"); }; Canvas.prototype.setWidth = function(width) { this.element.width = width; }; Canvas.prototype.getWidth = function() { return this.element.width; }; Canvas.prototype.setHeight = function(height) { this.element.width = height; }; Canvas.prototype.getHeight = function() { return this.element.height; }; Canvas.prototype.getContext = function() { return this.context; }; return Canvas; }}(); carl.Layer = (function() { "use strict"; function Layer() { }; Layer.prototype = new carl.Canvas(); return Layer; })();
source share