I found that using prototypes is very useful here. If you are not familiar with them, prototypes are part of objects that allow you to set your own variables and / or methods.
Doing something like:
Image.prototype.position = { x: 0, y: 0 } Image.prototype.onload = function(){ context.drawImage(this, this.position.x, this.position.y); }
Allows you to set position and draw on canvas without much difficulty.
The variable "position" allows you to move it on the canvas.
So you can do:
var myImg = new Image(); myImg.position.x = 20; myImg.position.y = 200; myImg.src = "http://www.google.com/intl/en_ALL/images/logo.gif";
and the image automatically draws on canvas in (20,200).
The prototype works for all HTML and native Javascript objects. So
Array.prototype.sum = function(){ var _sum = 0.0; for (var i=0; i<this.length; i++){ _sum += parseFloat(this[i]); } return _sum; }
gives a new function for all arrays.
but
var Bob; Bob.Prototype.sayHi = function(){ alert("Hello there."); }
won't work (for several reasons, but I'll just talk about prototypes).
A prototype is a sort property that contains all your properties / methods that you enter and is already in each of the HTML and your own Javascript objects (and not the ones you do).
Prototypes also make calling easy (you can do "myImg.position.x" instead of "myImg.prototype.position.x").
Also, if you define a variable, you should do it more like this.
var Bob = function(){ this.sayHi = function(){ alert("Hello there."); } }
TheCrzyMan
source share