Skip to content

Instantly share code, notes, and snippets.

@Rcomian
Created October 30, 2012 13:37
Show Gist options
  • Save Rcomian/3980232 to your computer and use it in GitHub Desktop.
Save Rcomian/3980232 to your computer and use it in GitHub Desktop.
Basic whiteboard class for demonstrations
function WhiteBoard(canvas, onLine) {
// Drawing
var ctx = canvas[0].getContext('2d');
var self = this;
this.randomColor = function () {
var col = [
Math.floor(Math.random() * 256),
Math.floor(Math.random() * 256),
Math.floor(Math.random() * 256)
];
col[Math.floor(Math.random() * 3)] = 0;
return col;
};
this.clear = function clear() {
ctx.fillStyle = 'rgb(255, 255, 255)';
ctx.fillRect(1, 1, canvas.width()-2, canvas.height()-2);
};
this.drawLine = function drawLine(points, color) {
if (points && points.length) {
ctx.beginPath();
ctx.strokeStyle = 'rgb(' + color.join(',') + ')';
ctx.moveTo(points[0].x, points[0].y);
var i;
for (i = 1; i < points.length; i += 1) {
ctx.lineTo(points[i].x, points[i].y);
}
ctx.stroke();
}
}
var mouseloc = null;
var points = null;
function coordsFromEvent(e) {
return { x: e.offsetX || (e.pageX - canvas.position().left),
y: e.offsetY || (e.pageY - canvas.position().top)};
}
function beginLine(pos) {
mouseloc = pos;
points = [];
points.push(pos);
}
function endline() {
if (mouseloc && points) {
onLine(points);
mouseloc = null;
points = null;
}
}
function doLine(pos) {
if (mouseloc && points && points.length < 1000) {
self.drawLine([mouseloc, pos], [196, 196, 196]);
mouseloc = pos;
points.push(pos);
}
}
// Mouse events
canvas.on('mousedown', function (e) {
if (e.which === 1) {
beginLine(coordsFromEvent(e));
}
});
canvas.on('mousemove', function (e) {
doLine(coordsFromEvent(e));
});
canvas.on('mouseup', endline);
canvas.on('mouseout', endline);
canvas.on('mouseleave', endline);
canvas.on('touchstart', function(e) {
e.preventDefault();
beginLine(coordsFromEvent(e.originalEvent.touches[0]));
});
canvas.on('touchend', endline);
canvas.on('touchcancel', endline);
canvas.on('touchleave', endline);
canvas.on('touchmove', function(e) {
e.preventDefault();
doLine(coordsFromEvent(e.originalEvent.touches[0]));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment