I'm trying to learn JavaScript, using an OO approach. This is my code:
/*global document, MouseEvent */
MouseEvent.prototype.mouseCoordinates = function () {
return {
'x' : this.pageX - this.target.offsetLeft,
'y' : this.pageY - this.target.offsetTop
};
};
(function () {
var Pencil = function () {},
Canvas = function () {
this.element = document.getElementById('canvas');
this.tool = new Pencil();
this.element.addEventListener('click', this.tool.draw, false);
},
c;
Pencil.prototype.draw = function (event) {
var context = event.target.getContext('2d'),
coordinates = event.mouseCoordinates();
context.fillRect(coordinates.x, coordinates.y, 5, 5);
};
c = new Canvas();
}());
I'm trying to do something like MS Paint. So, I've created a Canvas object and a Pencil one. I am able to do it using a procedural approach but I don't want to. I don't want to use any library now, I'm just studying.
I've these questions:
Are there any good practice to register events? Should I register events using the object constructor?
My canvas object has a tool (pencil in this case) object. Conceptually it's not good. My canvas should not have a tool object. It must provides a surface to draw and that's it! But, it's there as a callback (click event). How could I solve this?
Every tool will have the same interface but different behaviours. Could I create interfaces using Javascript?
What else can I improve?
UPDATE:
(function () {
var pencil = {
draw : function (event) {
var context = event.target.getContext('2d'),
coordinates = event.mouseCoordinates();
context.fillRect(coordinates.x, coordinates.y, 5, 5);
}
},
currentTool = pencil,
canvas = (function () {
var object = {};
object.element = document.getElementById('canvas');
object.element.addEventListener('click', function (event) {
currentTool.draw(event);
}, false);
return object;
}());
}());
I've followed all the tips (thank you, I appreciate your help!). What do you think? Now I have a "global" currentTool variable. What do you think about it? Thanks.
Thank you.