'use strict';
(function() {
var socket = io();
var canvas = document.getElementsByClassName('whiteboard')[0];
var colors = document.getElementsByClassName('color');
var context = canvas.getContext('2d');
var current = {
color: 'black'
};
var drawing = false;
canvas.addEventListener('mousedown', onMouseDown, false);
canvas.addEventListener('mouseup', onMouseUp, false);
canvas.addEventListener('mouseout', onMouseUp, false);
canvas.addEventListener('mousemove', throttle(onMouseMove, 10), false);
for (var i = 0; i < colors.length; i++){
colors[i].addEventListener('click', onColorUpdate, false);
}
socket.on('drawing', onDrawingEvent);
window.addEventListener('resize', onResize, false);
onResize();
function drawLine(x0, y0, x1, y1, color, emit){
context.beginPath();
context.moveTo(x0, y0);
context.lineTo(x1, y1);
context.strokeStyle = color;
context.lineWidth = 2;
context.stroke();
context.closePath();
if (!emit) { return; }
var w = canvas.width;
var h = canvas.height;
socket.emit('drawing', {
x0: x0 / w,
y0: y0 / h,
x1: x1 / w,
y1: y1 / h,
color: color
});
}
function onMouseDown(e){
drawing = true;
current.x = e.clientX;
current.y = e.clientY;
}
function onMouseUp(e){
if (!drawing) { return; }
drawing = false;
drawLine(current.x, current.y, e.clientX, e.clientY, current.color, true);
}
function onMouseMove(e){
if (!drawing) { return; }
drawLine(current.x, current.y, e.clientX, e.clientY, current.color, true);
current.x = e.clientX;
current.y = e.clientY;
}
function onColorUpdate(e){
current.color = e.target.className.split(' ')[1];
}
// limit the number of events per second
function throttle(callback, delay) {
var previousCall = new Date().getTime();
return function() {
var time = new Date().getTime();
if ((time - previousCall) >= delay) {
previousCall = time;
callback.apply(null, arguments);
}
};
}
function onDrawingEvent(data){
var w = canvas.width;
var h = canvas.height;
drawLine(data.x0 * w, data.y0 * h, data.x1 * w, data.y1 * h, data.color);
}
// make the canvas fill its parent
function onResize() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
})()
whiteboard
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- runtime源码下载地址http://opensource.apple.com/tarballs/objc4/ ...