Ok, so I'm working on a small html5 canvas drawing library and I'm having a slight problem, here's the code (fiddle below):
var drawr = {
init: function (canvas_id, canvasWidth, canvasHeight) { //height & width are optional
this.canvas_id = document.getElementById(canvas_id);
this.canvasWidth = canvasWidth;
this.canvasHeight = canvasHeight;
this.context = this.canvas_id.getContext('2d');
if (canvasWidth) {
this.canvas_id.width = canvasWidth;
}
if (canvasHeight) {
this.canvas_id.height = canvasHeight;
}
},
//magic line drawing function
ctx: function (a, b, x, y, dLineColor, dLineWidth) { //lineWidth & lineColor are optional; defaults are 1px & 'black'
this.context.lineJoin = 'round';
this.context.beginPath();
this.context.moveTo(a, b);
this.context.lineTo(x, y);
this.context.closePath();
this.context.strokeStyle = dLineColor;
this.context.lineWidth = dLineWidth;
this.context.stroke();
},
//destroy event handlers to prevent drawing
destroy: function () {
//destroy event handlers
},
draw: function (lineColor, lineWidth) {
//create some utilities for draw function to use
var localPen = {};
var drawing = false;
var canvasPos = {
x: this.canvas_id.offsetLeft,
y: this.canvas_id.offsetTop
}
//initiate event handlers
this.canvas_id.addEventListener('mousedown', addDraw, false);
function addDraw(e) {
drawing = true;
console.log(drawing);
localPen.x = e.pageX - canvasPos.x;
localPen.y = e.pageY - canvasPos.y;
};
this.canvas_id.addEventListener('mousemove', function (e) {
var drawTo = {
x: e.pageX - canvasPos.x,
y: e.pageY - canvasPos.y
}
if (drawing) {
drawr.ctx(localPen.x, localPen.y, drawTo.x, drawTo.y, lineColor, lineWidth);
}
localPen.x = drawTo.x;
localPen.y = drawTo.y;
});
this.canvas_id.addEventListener('mouseup', function (e) {
drawing = false;
});
this.canvas_id.addEventListener('mouseleave', function (e) {
drawing = false;
});
}
}
drawr.init('my_canvas');
drawr.draw('red', 10);
drawr.draw('blue', 5);
What I'm trying to accomplish here is this: when I call drawr.draw(); a second (or third, etc) for it to override the previous function. How should I go about this? As you can see in my fiddle each instance simultaneously runs.
Feel free to edit, update, delete, yell at me for bad code, etc.