【发布时间】:2014-09-24 01:59:06
【问题描述】:
好的,所以我正在开发一个小型 html5 画布绘图库,但我遇到了一个小问题,这是代码(下面的小提琴):
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);
我在这里想要完成的是:当我调用 drawr.draw(); 时,第二个(或第三个等)它会覆盖之前的函数。我该怎么办?正如您在我的fiddle 中看到的那样,每个实例同时运行。
随意编辑、更新、删除、对错误代码大吼大叫等。
【问题讨论】:
标签: javascript html