A Canvas Constructor Function -
What does a canvas constructor function look like? I had thought of something like this but some is clearly wrong.
function canvas (canvas) {this.canvas = document.createElement ('canvas'); This.width = 400; This.height = 400; This.style.border = "1px solid"; Document.body.appendChild (canvas); This.context = canvas.getContext ('2d'); } Var canvas1 = new canvas ('canvas 1');
You are only referring to this
It's self, not the canvas you created. This should work:
function canvas (canvasad) {this.canvas = document.createElement ('canvas'); This.canvas.width = 400; This.canvas.height = 400; This.context = this.canvas.getContext ('2d'); This.canvas.style.border = "1px solid"; This.canvas.id = canvasID; // Use the name document.body.appendChild (this.canvas); } Var canvas1 = new canvas ('canvas 1'); Canvas1.context.fillRect (0, 0, 400, 400);
When you are inside the function scope, refers to this
object. You are setting a new property on the object (canvas etc.) so that the object Use the same property name inside to reference them, i.e. this.canvas
and so on
Actually do not mention id / name, though as you are already in the context of the element in this object unless you have CSS or Inquiry
You can also pass in width and height or use default values if they are not provided:
function canvas (canvas, width, height } {This.canvas = Document.createElement ('canvas'); This.canvas.width = width || 400; This.canvas.height = Height || 400; This.context = this.canvas.getContext ('2d'); This.canvas.style.border = "1px solid"; This.canvas.id = canvasID; // Use the name document.body.appendChild (this.canvas); } Var canvas1 = new canvas ('canvas 1'); // 400x400 var canvas2 = new canvas ('Big Canvas', 2000, 500); // 2000x500
Comments
Post a Comment