fix spelling error and format code

This commit is contained in:
cracker 2018-09-08 19:15:23 +02:00
parent 200391c613
commit 3efb36ac19
3 changed files with 653 additions and 648 deletions

View File

@ -1,11 +1,13 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<title>Whiteboard</title> <title>Whiteboard</title>
<!--- JS References -!--> <!--- JS References -!-->
<script type="text/javascript" src="./js/jquery-3.2.1.min.js"></script> <script type="text/javascript" src="./js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="./js/jquery-ui.min.js"></script> <!--- for dragabbles -!--> <script type="text/javascript" src="./js/jquery-ui.min.js"></script>
<!--- for dragabbles -!-->
<script type="text/javascript" src="./js/socketio2.0.4.min.js"></script> <script type="text/javascript" src="./js/socketio2.0.4.min.js"></script>
<script type="text/javascript" src="./js/jqColorPicker.min.js"></script> <script type="text/javascript" src="./js/jqColorPicker.min.js"></script>
@ -18,6 +20,7 @@
<link href="./css/main.css" rel="stylesheet"> <link href="./css/main.css" rel="stylesheet">
</head> </head>
<body style="position: relative; margin: 0px; height: 100vh; width: 100%; overflow: hidden;"> <body style="position: relative; margin: 0px; height: 100vh; width: 100%; overflow: hidden;">
<!---Whiteboard container -!--> <!---Whiteboard container -!-->
<div style="height: 100vh; width: 100%;" id="whiteboardContainer"></div> <div style="height: 100vh; width: 100%;" id="whiteboardContainer"></div>
@ -59,7 +62,8 @@
<div style="width: 190px; height: 44px; border: 1px solid green;" class="btn-group"> <div style="width: 190px; height: 44px; border: 1px solid green;" class="btn-group">
<img style="position: absolute; left: 11px; top: 16px; height:14px; width:130px;" src="./img/slider-background.svg"> <img style="position: absolute; left: 11px; top: 16px; height:14px; width:130px;" src="./img/slider-background.svg">
<input title="Thickness" id="whiteboardThicknessSlider" style="position: absolute; left:9px; width: 130px; top: 15px;" type="range" min="1" max="50" value="3"> <input title="Thickness" id="whiteboardThicknessSlider" style="position: absolute; left:9px; width: 130px; top: 15px;" type="range"
min="1" max="50" value="3">
<div title="Colorpicker" style="position: absolute; left: 155px; top: 10px; width: 26px; height: 23px; border-radius: 3px; overflow: hidden; border: 1px solid darkgrey;"> <div title="Colorpicker" style="position: absolute; left: 155px; top: 10px; width: 26px; height: 23px; border-radius: 3px; overflow: hidden; border: 1px solid darkgrey;">
<div id="whiteboardColorpicker" value="#000000" style="width: 40px; height: 35px; border: 0px; padding: 0px; position: relative; top: 0px; left: -5px;"></div> <div id="whiteboardColorpicker" value="#000000" style="width: 40px; height: 35px; border: 0px; padding: 0px; position: relative; top: 0px; left: -5px;"></div>
</div> </div>
@ -85,7 +89,8 @@
<i class="far fa-file-alt"></i> <i class="far fa-file-alt"></i>
<i style="position: absolute; top: 3px; left: 2px; color: #000000; font-size: 0.5em; " class="fas fa-upload"></i> <i style="position: absolute; top: 3px; left: 2px; color: #000000; font-size: 0.5em; " class="fas fa-upload"></i>
</button> </button>
<input style="display:none;" id="myFile" type="file"/> <input style="display:none;" id="myFile" type="file" />
</div> </div>
</body> </body>
</html> </html>

View File

@ -1,17 +1,17 @@
var whiteboardId = getQueryVariable("whiteboardid"); var whiteboardId = getQueryVariable("whiteboardid");
whiteboardId = whiteboardId || "myNewWhiteboard"; whiteboardId = whiteboardId || "myNewWhiteboard";
var myUsername = getQueryVariable("username"); var myUsername = getQueryVariable("username");
myUsername = myUsername || "unkonwn"+(Math.random()+"").substring(2,6); myUsername = myUsername || "unknown" + (Math.random() + "").substring(2, 6);
var url = document.URL.substr(0,document.URL.lastIndexOf('/')); var url = document.URL.substr(0, document.URL.lastIndexOf('/'));
var signaling_socket = null; var signaling_socket = null;
var urlSplit = url.split("/"); var urlSplit = url.split("/");
var subdir = ""; var subdir = "";
for(var i=3;i<urlSplit.length;i++) { for (var i = 3; i < urlSplit.length; i++) {
subdir = subdir+'/'+urlSplit[i]; subdir = subdir + '/' + urlSplit[i];
} }
if(subdir !="") { if (subdir != "") {
signaling_socket = io("",{"path":subdir+"/socket.io"}); //Connect even if we are in a subdir behind a reverse proxy signaling_socket = io("", { "path": subdir + "/socket.io" }); //Connect even if we are in a subdir behind a reverse proxy
} else { } else {
signaling_socket = io(); signaling_socket = io();
} }
@ -30,16 +30,16 @@ signaling_socket.on('connect', function () {
signaling_socket.emit('joinWhiteboard', whiteboardId); signaling_socket.emit('joinWhiteboard', whiteboardId);
}); });
$(document).ready(function() { $(document).ready(function () {
whiteboard.loadWhiteboard("#whiteboardContainer", { //Load the whiteboard whiteboard.loadWhiteboard("#whiteboardContainer", { //Load the whiteboard
whiteboardId : whiteboardId, whiteboardId: whiteboardId,
username : myUsername, username: myUsername,
sendFunction : function(content) { sendFunction: function (content) {
signaling_socket.emit('drawToWhiteboard', content); signaling_socket.emit('drawToWhiteboard', content);
} }
}); });
$.get( subdir+"/loadwhiteboard", { wid: whiteboardId } ).done(function( data ) { $.get(subdir + "/loadwhiteboard", { wid: whiteboardId }).done(function (data) {
whiteboard.loadData(data) whiteboard.loadData(data)
}); });
@ -47,25 +47,25 @@ $(document).ready(function() {
Whiteboard actions Whiteboard actions
/----------------*/ /----------------*/
$("#whiteboardTrashBtn").click(function() { $("#whiteboardTrashBtn").click(function () {
whiteboard.clearWhiteboard(); whiteboard.clearWhiteboard();
}); });
$("#whiteboardUndoBtn").click(function() { $("#whiteboardUndoBtn").click(function () {
whiteboard.undoWhiteboardClick(); whiteboard.undoWhiteboardClick();
}); });
$(".whiteboardTool").click(function() { $(".whiteboardTool").click(function () {
$(".whiteboardTool").removeClass("active"); $(".whiteboardTool").removeClass("active");
$(this).addClass("active"); $(this).addClass("active");
whiteboard.setTool($(this).attr("tool")); whiteboard.setTool($(this).attr("tool"));
}); });
$("#addImgToCanvasBtn").click(function() { $("#addImgToCanvasBtn").click(function () {
alert("Just drag and drop images in!"); alert("Just drag and drop images in!");
}); });
$("#saveAsImageBtn").click(function() { $("#saveAsImageBtn").click(function () {
var imgData = whiteboard.getImageDataBase64(); var imgData = whiteboard.getImageDataBase64();
var a = document.createElement('a'); var a = document.createElement('a');
a.href = imgData; a.href = imgData;
@ -75,10 +75,10 @@ $(document).ready(function() {
document.body.removeChild(a); document.body.removeChild(a);
}); });
$("#saveAsJSONBtn").click(function() { $("#saveAsJSONBtn").click(function () {
var imgData = whiteboard.getImageDataJson(); var imgData = whiteboard.getImageDataJson();
var a = window.document.createElement('a'); var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([imgData], {type: 'text/json'})); a.href = window.URL.createObjectURL(new Blob([imgData], { type: 'text/json' }));
a.download = 'whiteboard.json'; a.download = 'whiteboard.json';
// Append anchor to body. // Append anchor to body.
document.body.appendChild(a); document.body.appendChild(a);
@ -87,18 +87,18 @@ $(document).ready(function() {
document.body.removeChild(a); document.body.removeChild(a);
}); });
$("#uploadJsonBtn").click(function() { $("#uploadJsonBtn").click(function () {
$("#myFile").click(); $("#myFile").click();
}); });
$("#myFile").on("change", function() { $("#myFile").on("change", function () {
var file = document.getElementById("myFile").files[0]; var file = document.getElementById("myFile").files[0];
var reader = new FileReader(); var reader = new FileReader();
reader.onload = function (e) { reader.onload = function (e) {
try { try {
var j = JSON.parse(e.target.result); var j = JSON.parse(e.target.result);
whiteboard.loadJsonData(j); whiteboard.loadJsonData(j);
} catch(e) { } catch (e) {
alert("File was not a valid JSON!"); alert("File was not a valid JSON!");
} }
}; };
@ -107,14 +107,14 @@ $(document).ready(function() {
}); });
var dragCounter = 0; var dragCounter = 0;
$('#whiteboardContainer').on("dragenter", function(e) { $('#whiteboardContainer').on("dragenter", function (e) {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
dragCounter++; dragCounter++;
whiteboard.dropIndicator.show(); whiteboard.dropIndicator.show();
}); });
$('#whiteboardContainer').on("dragleave", function(e) { $('#whiteboardContainer').on("dragleave", function (e) {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
dragCounter--; dragCounter--;
@ -123,23 +123,22 @@ $(document).ready(function() {
} }
}); });
$("#whiteboardThicknessSlider").on("change", function() { $("#whiteboardThicknessSlider").on("change", function () {
whiteboard.thickness = $(this).val(); whiteboard.thickness = $(this).val();
}); });
$('#whiteboardContainer').on('drop', function(e) { //Handle drag & drop $('#whiteboardContainer').on('drop', function (e) { //Handle drag & drop
if(e.originalEvent.dataTransfer){ if (e.originalEvent.dataTransfer) {
if(e.originalEvent.dataTransfer.files.length) { //File from harddisc if (e.originalEvent.dataTransfer.files.length) { //File from harddisc
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
var filename = e.originalEvent.dataTransfer.files[0]["name"]; var filename = e.originalEvent.dataTransfer.files[0]["name"];
if(isImageFileName(filename)) { if (isImageFileName(filename)) {
var blob = e.originalEvent.dataTransfer.files[0]; var blob = e.originalEvent.dataTransfer.files[0];
var reader = new window.FileReader(); var reader = new window.FileReader();
reader.readAsDataURL(blob); reader.readAsDataURL(blob);
reader.onloadend = function() { reader.onloadend = function () {
console.log("Uploading image!");
base64data = reader.result; base64data = reader.result;
uploadImgAndAddToWhiteboard(base64data); uploadImgAndAddToWhiteboard(base64data);
} }
@ -151,19 +150,19 @@ $(document).ready(function() {
var imageUrl = e.originalEvent.dataTransfer.getData('text/html'); var imageUrl = e.originalEvent.dataTransfer.getData('text/html');
var rex = /src="?([^"\s]+)"?\s*/; var rex = /src="?([^"\s]+)"?\s*/;
var url = rex.exec(imageUrl); var url = rex.exec(imageUrl);
if(url && url.length > 1) { if (url && url.length > 1) {
url = url[1]; url = url[1];
} else { } else {
url = ""; url = "";
} }
isValidImageUrl(fileUrl, function(isImage) { isValidImageUrl(fileUrl, function (isImage) {
if(isImage && isImageFileName(url)) { if (isImage && isImageFileName(url)) {
whiteboard.addImgToCanvasByUrl(fileUrl); whiteboard.addImgToCanvasByUrl(fileUrl);
} else { } else {
isValidImageUrl(url, function(isImage) { isValidImageUrl(url, function (isImage) {
if(isImage) { if (isImage) {
if(isImageFileName(url)) { if (isImageFileName(url)) {
whiteboard.addImgToCanvasByUrl(url); whiteboard.addImgToCanvasByUrl(url);
} else { } else {
var blob = items[i].getAsFile(); var blob = items[i].getAsFile();
@ -182,46 +181,46 @@ $(document).ready(function() {
}); });
$('#whiteboardColorpicker').colorPicker({ $('#whiteboardColorpicker').colorPicker({
renderCallback : function(elm) { renderCallback: function (elm) {
whiteboard.drawcolor = elm.val(); whiteboard.drawcolor = elm.val();
} }
}); });
}); });
//Prevent site from changing tab on drag&drop //Prevent site from changing tab on drag&drop
window.addEventListener("dragover",function(e){ window.addEventListener("dragover", function (e) {
e = e || event; e = e || event;
e.preventDefault(); e.preventDefault();
},false); }, false);
window.addEventListener("drop",function(e){ window.addEventListener("drop", function (e) {
e = e || event; e = e || event;
e.preventDefault(); e.preventDefault();
},false); }, false);
function uploadImgAndAddToWhiteboard(base64data) { function uploadImgAndAddToWhiteboard(base64data) {
var date = (+new Date()); var date = (+new Date());
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: document.URL.substr(0,document.URL.lastIndexOf('/'))+'/upload', url: document.URL.substr(0, document.URL.lastIndexOf('/')) + '/upload',
data: { data: {
'imagedata': base64data, 'imagedata': base64data,
'whiteboardId' : whiteboardId, 'whiteboardId': whiteboardId,
'date' : date 'date': date
}, },
success: function(msg){ success: function (msg) {
var filename = whiteboardId+"_"+date+".png"; var filename = whiteboardId + "_" + date + ".png";
whiteboard.addImgToCanvasByUrl(document.URL.substr(0,document.URL.lastIndexOf('/'))+"/uploads/"+filename); //Add image to canvas whiteboard.addImgToCanvasByUrl(document.URL.substr(0, document.URL.lastIndexOf('/')) + "/uploads/" + filename); //Add image to canvas
console.log("Image uploaded!"); console.log("Image uploaded!");
}, },
error : function(err) { error: function (err) {
console.error("Failed to upload frame: "+JSON.stringify(err)); console.error("Failed to upload frame: " + JSON.stringify(err));
} }
}); });
} }
function isImageFileName(filename) { function isImageFileName(filename) {
var ending = filename.split(".")[filename.split(".").length-1]; var ending = filename.split(".")[filename.split(".").length - 1];
if(ending.toLowerCase()=="png" || ending.toLowerCase()=="jpg" || ending.toLowerCase()=="jpeg" || ending.toLowerCase()=="gif" || ending.toLowerCase()=="tiff") { if (ending.toLowerCase() == "png" || ending.toLowerCase() == "jpg" || ending.toLowerCase() == "jpeg" || ending.toLowerCase() == "gif" || ending.toLowerCase() == "tiff") {
return true; return true;
} }
return false; return false;
@ -244,7 +243,7 @@ function isValidImageUrl(url, callback) { //Check if given url it is a vaild img
img.src = url; img.src = url;
} }
window.addEventListener("paste", function(e) { //Even do copy & paste from clipboard window.addEventListener("paste", function (e) { //Even do copy & paste from clipboard
if (e.clipboardData) { if (e.clipboardData) {
var items = e.clipboardData.items; var items = e.clipboardData.items;
if (items) { if (items) {
@ -256,7 +255,7 @@ window.addEventListener("paste", function(e) { //Even do copy & paste from clipb
var reader = new window.FileReader(); var reader = new window.FileReader();
reader.readAsDataURL(blob); reader.readAsDataURL(blob);
reader.onloadend = function() { reader.onloadend = function () {
console.log("Uploading image!"); console.log("Uploading image!");
base64data = reader.result; base64data = reader.result;
uploadImgAndAddToWhiteboard(base64data); uploadImgAndAddToWhiteboard(base64data);
@ -270,7 +269,7 @@ window.addEventListener("paste", function(e) { //Even do copy & paste from clipb
function getQueryVariable(variable) { function getQueryVariable(variable) {
var query = window.location.search.substring(1); var query = window.location.search.substring(1);
var vars = query.split("&"); var vars = query.split("&");
for (var i=0;i<vars.length;i++) { for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("="); var pair = vars[i].split("=");
if (pair[0] == variable) { if (pair[0] == variable) {
return pair[1]; return pair[1];

View File

@ -1,37 +1,37 @@
var whiteboard = { var whiteboard = {
canvas : null, canvas: null,
ctx : null, ctx: null,
drawcolor : "black", drawcolor: "black",
tool : "pen", tool: "pen",
thickness : 4, thickness: 4,
prevX : null, prevX: null,
prevY : null, prevY: null,
drawFlag : false, drawFlag: false,
oldGCO : null, oldGCO: null,
mouseover : false, mouseover: false,
lineCap : "round", //butt, square lineCap: "round", //butt, square
backgroundGrid : null, backgroundGrid: null,
canvasElement : null, canvasElement: null,
cursorContainer : null, cursorContainer: null,
imgContainer : null, imgContainer: null,
svgContainer : null, //For draw prev svgContainer: null, //For draw prev
mouseOverlay : null, mouseOverlay: null,
ownCursor : null, ownCursor: null,
drawBuffer : [], drawBuffer: [],
drawId : 0, //Used for undo function drawId: 0, //Used for undo function
imgDragActive : false, imgDragActive: false,
settings : { settings: {
whiteboardId : "0", whiteboardId: "0",
username : "unknown", username: "unknown",
sendFunction : null, sendFunction: null,
canvasWidth : 3000, canvasWidth: 3000,
canvasHeight : 2000, canvasHeight: 2000,
backgroundGridUrl : './img/KtEBa2.png' backgroundGridUrl: './img/KtEBa2.png'
}, },
loadWhiteboard : function(whiteboardContainer, newSettings) { loadWhiteboard: function (whiteboardContainer, newSettings) {
var svgns = "http://www.w3.org/2000/svg"; var svgns = "http://www.w3.org/2000/svg";
var _this = this; var _this = this;
for(var i in newSettings) { for (var i in newSettings) {
this.settings[i] = newSettings[i]; this.settings[i] = newSettings[i];
} }
this.settings["username"] = this.settings["username"].replace(/[^0-9a-z]/gi, ''); this.settings["username"] = this.settings["username"].replace(/[^0-9a-z]/gi, '');
@ -43,13 +43,13 @@ var whiteboard = {
var svgCirle = null; var svgCirle = null;
var latestTouchCoods = null; var latestTouchCoods = null;
//Background //Background
_this.backgroundGrid = $('<div style="position: absolute; left:0px; top:0; opacity: 0.2; background-image:url(\''+_this.settings["backgroundGridUrl"]+'\'); height: 100%; width: 100%;"></div>'); _this.backgroundGrid = $('<div style="position: absolute; left:0px; top:0; opacity: 0.2; background-image:url(\'' + _this.settings["backgroundGridUrl"] + '\'); height: 100%; width: 100%;"></div>');
_this.imgContainer = $('<div style="position: absolute; left:0px; top:0; height: 100%; width: 100%;"></div>'); _this.imgContainer = $('<div style="position: absolute; left:0px; top:0; height: 100%; width: 100%;"></div>');
//Canvas //Canvas
_this.canvasElement = $('<canvas id="whiteboardCanvas" style="position: absolute; left:0px; top:0; cursor:crosshair;"></canvas>'); _this.canvasElement = $('<canvas id="whiteboardCanvas" style="position: absolute; left:0px; top:0; cursor:crosshair;"></canvas>');
_this.svgContainer = $('<svg style="position: absolute; top:0px; left:0px;" width="'+_this.settings.canvasWidth+'" height="'+_this.settings.canvasHeight+'"></svg>'); _this.svgContainer = $('<svg style="position: absolute; top:0px; left:0px;" width="' + _this.settings.canvasWidth + '" height="' + _this.settings.canvasHeight + '"></svg>');
_this.cursorContainer = $('<div style="position: absolute; left:0px; top:0; height: 100%; width: 100%;"></div>'); _this.cursorContainer = $('<div style="position: absolute; left:0px; top:0; height: 100%; width: 100%;"></div>');
@ -59,60 +59,60 @@ var whiteboard = {
$(whiteboardContainer).append(_this.backgroundGrid).append(_this.imgContainer).append( _this.canvasElement).append(_this.svgContainer).append(_this.dropIndicator).append(_this.cursorContainer).append(this.mouseOverlay); $(whiteboardContainer).append(_this.backgroundGrid).append(_this.imgContainer).append(_this.canvasElement).append(_this.svgContainer).append(_this.dropIndicator).append(_this.cursorContainer).append(this.mouseOverlay);
this.canvas = $("#whiteboardCanvas")[0]; this.canvas = $("#whiteboardCanvas")[0];
this.canvas.height = _this.settings.canvasHeight; this.canvas.height = _this.settings.canvasHeight;
this.canvas.width = _this.settings.canvasWidth; this.canvas.width = _this.settings.canvasWidth;
this.ctx = this.canvas.getContext("2d"); this.ctx = this.canvas.getContext("2d");
this.oldGCO = this.ctx.globalCompositeOperation; this.oldGCO = this.ctx.globalCompositeOperation;
$(_this.mouseOverlay).on("mousedown touchstart", function(e) { $(_this.mouseOverlay).on("mousedown touchstart", function (e) {
if(_this.imgDragActive) { if (_this.imgDragActive) {
return; return;
} }
_this.drawFlag = true; _this.drawFlag = true;
_this.prevX = (e.offsetX || e.pageX - $(e.target).offset().left); _this.prevX = (e.offsetX || e.pageX - $(e.target).offset().left);
_this.prevY = (e.offsetY || e.pageY - $(e.target).offset().top); _this.prevY = (e.offsetY || e.pageY - $(e.target).offset().top);
if(!_this.prevX || !_this.prevY) { if (!_this.prevX || !_this.prevY) {
var touche= e.touches[0]; var touche = e.touches[0];
_this.prevX = touche.clientX - $(_this.mouseOverlay).offset().left; _this.prevX = touche.clientX - $(_this.mouseOverlay).offset().left;
_this.prevY = touche.clientY - $(_this.mouseOverlay).offset().top; _this.prevY = touche.clientY - $(_this.mouseOverlay).offset().top;
latestTouchCoods = [_this.prevX, _this.prevY]; latestTouchCoods = [_this.prevX, _this.prevY];
} }
if(_this.tool==="pen") { if (_this.tool === "pen") {
_this.drawPenLine(_this.prevX, _this.prevY, _this.prevX, _this.prevY, _this.drawcolor, _this.thickness); _this.drawPenLine(_this.prevX, _this.prevY, _this.prevX, _this.prevY, _this.drawcolor, _this.thickness);
_this.sendFunction({"t":_this.tool,"d":[_this.prevX, _this.prevY, _this.prevX, _this.prevY], "c":_this.drawcolor, "th":_this.thickness}); _this.sendFunction({ "t": _this.tool, "d": [_this.prevX, _this.prevY, _this.prevX, _this.prevY], "c": _this.drawcolor, "th": _this.thickness });
} else if(_this.tool==="eraser") { } else if (_this.tool === "eraser") {
_this.drawEraserLine(_this.prevX, _this.prevY, _this.prevX, _this.prevY, _this.thickness); _this.drawEraserLine(_this.prevX, _this.prevY, _this.prevX, _this.prevY, _this.thickness);
_this.sendFunction({"t":_this.tool,"d":[_this.prevX, _this.prevY, _this.prevX, _this.prevY], "th":_this.thickness}); _this.sendFunction({ "t": _this.tool, "d": [_this.prevX, _this.prevY, _this.prevX, _this.prevY], "th": _this.thickness });
} else if(_this.tool==="line") { } else if (_this.tool === "line") {
startCoords = [_this.prevX, _this.prevY]; startCoords = [_this.prevX, _this.prevY];
svgLine = document.createElementNS(svgns,'line'); svgLine = document.createElementNS(svgns, 'line');
svgLine.setAttribute('stroke','gray'); svgLine.setAttribute('stroke', 'gray');
svgLine.setAttribute('stroke-dasharray','5, 5'); svgLine.setAttribute('stroke-dasharray', '5, 5');
svgLine.setAttribute('x1',_this.prevX); svgLine.setAttribute('x1', _this.prevX);
svgLine.setAttribute('y1',_this.prevY); svgLine.setAttribute('y1', _this.prevY);
svgLine.setAttribute('x2',_this.prevX+1); svgLine.setAttribute('x2', _this.prevX + 1);
svgLine.setAttribute('y2',_this.prevY+1); svgLine.setAttribute('y2', _this.prevY + 1);
_this.svgContainer.append(svgLine); _this.svgContainer.append(svgLine);
} else if(_this.tool==="rect" || _this.tool==="recSelect") { } else if (_this.tool === "rect" || _this.tool === "recSelect") {
_this.svgContainer.find("rect").remove(); _this.svgContainer.find("rect").remove();
svgRect = document.createElementNS(svgns,'rect'); svgRect = document.createElementNS(svgns, 'rect');
svgRect.setAttribute('stroke','gray'); svgRect.setAttribute('stroke', 'gray');
svgRect.setAttribute('stroke-dasharray','5, 5'); svgRect.setAttribute('stroke-dasharray', '5, 5');
svgRect.setAttribute('style','fill-opacity:0.0;'); svgRect.setAttribute('style', 'fill-opacity:0.0;');
svgRect.setAttribute('x', _this.prevX); svgRect.setAttribute('x', _this.prevX);
svgRect.setAttribute('y', _this.prevY); svgRect.setAttribute('y', _this.prevY);
svgRect.setAttribute('width',0); svgRect.setAttribute('width', 0);
svgRect.setAttribute('height',0); svgRect.setAttribute('height', 0);
_this.svgContainer.append(svgRect); _this.svgContainer.append(svgRect);
startCoords = [_this.prevX, _this.prevY]; startCoords = [_this.prevX, _this.prevY];
} else if(_this.tool==="circle") { } else if (_this.tool === "circle") {
svgCirle = document.createElementNS(svgns,'circle'); svgCirle = document.createElementNS(svgns, 'circle');
svgCirle.setAttribute('stroke','gray'); svgCirle.setAttribute('stroke', 'gray');
svgCirle.setAttribute('stroke-dasharray','5, 5'); svgCirle.setAttribute('stroke-dasharray', '5, 5');
svgCirle.setAttribute('style','fill-opacity:0.0;'); svgCirle.setAttribute('style', 'fill-opacity:0.0;');
svgCirle.setAttribute('cx', _this.prevX); svgCirle.setAttribute('cx', _this.prevX);
svgCirle.setAttribute('cy', _this.prevY); svgCirle.setAttribute('cy', _this.prevY);
svgCirle.setAttribute('r', 0); svgCirle.setAttribute('r', 0);
@ -121,179 +121,180 @@ var whiteboard = {
} }
}); });
$(_this.mouseOverlay).on("mousemove touchmove", function(e) { $(_this.mouseOverlay).on("mousemove touchmove", function (e) {
e.preventDefault(); e.preventDefault();
if(_this.imgDragActive) { if (_this.imgDragActive) {
return; return;
} }
var currX = (e.offsetX || e.pageX - $(e.target).offset().left); var currX = (e.offsetX || e.pageX - $(e.target).offset().left);
var currY = (e.offsetY || e.pageY - $(e.target).offset().top); var currY = (e.offsetY || e.pageY - $(e.target).offset().top);
window.requestAnimationFrame(function() { window.requestAnimationFrame(function () {
if((!currX || !currY) && e.touches && e.touches[0]) { if ((!currX || !currY) && e.touches && e.touches[0]) {
var touche= e.touches[0]; var touche = e.touches[0];
currX = touche.clientX - $(_this.mouseOverlay).offset().left; currX = touche.clientX - $(_this.mouseOverlay).offset().left;
currY = touche.clientY - $(_this.mouseOverlay).offset().top; currY = touche.clientY - $(_this.mouseOverlay).offset().top;
latestTouchCoods = [currX, currY]; latestTouchCoods = [currX, currY];
} }
if(_this.drawFlag) { if (_this.drawFlag) {
if(_this.tool==="pen") { if (_this.tool === "pen") {
_this.drawPenLine(currX, currY, _this.prevX, _this.prevY, _this.drawcolor, _this.thickness); _this.drawPenLine(currX, currY, _this.prevX, _this.prevY, _this.drawcolor, _this.thickness);
_this.sendFunction({"t":_this.tool,"d":[currX, currY, _this.prevX, _this.prevY], "c":_this.drawcolor, "th":_this.thickness}); _this.sendFunction({ "t": _this.tool, "d": [currX, currY, _this.prevX, _this.prevY], "c": _this.drawcolor, "th": _this.thickness });
} else if(_this.tool=="eraser") { } else if (_this.tool == "eraser") {
_this.drawEraserLine(currX, currY, _this.prevX, _this.prevY, _this.thickness); _this.drawEraserLine(currX, currY, _this.prevX, _this.prevY, _this.thickness);
_this.sendFunction({"t":_this.tool,"d":[currX, currY, _this.prevX, _this.prevY], "th":_this.thickness}); _this.sendFunction({ "t": _this.tool, "d": [currX, currY, _this.prevX, _this.prevY], "th": _this.thickness });
} }
_this.prevX =currX; _this.prevX = currX;
_this.prevY =currY; _this.prevY = currY;
} }
if(_this.tool==="eraser") { if (_this.tool === "eraser") {
var left = currX-_this.thickness; var left = currX - _this.thickness;
var top = currY-_this.thickness; var top = currY - _this.thickness;
_this.ownCursor.css({"top":top+"px", "left":left+"px"}); _this.ownCursor.css({ "top": top + "px", "left": left + "px" });
} else if(_this.tool==="pen") { } else if (_this.tool === "pen") {
var left = currX-_this.thickness/2; var left = currX - _this.thickness / 2;
var top = currY-_this.thickness/2; var top = currY - _this.thickness / 2;
_this.ownCursor.css({"top":top+"px", "left":left+"px"}); _this.ownCursor.css({ "top": top + "px", "left": left + "px" });
} else if(_this.tool==="line") { } else if (_this.tool === "line") {
if(svgLine) { if (svgLine) {
if(shiftPressed) { if (shiftPressed) {
var angs = getRoundedAngles(currX, currY); var angs = getRoundedAngles(currX, currY);
currX = angs.x; currX = angs.x;
currY = angs.y; currY = angs.y;
} }
svgLine.setAttribute('x2',currX); svgLine.setAttribute('x2', currX);
svgLine.setAttribute('y2',currY); svgLine.setAttribute('y2', currY);
} }
} else if(_this.tool==="rect" || (_this.tool==="recSelect" && _this.drawFlag)) { } else if (_this.tool === "rect" || (_this.tool === "recSelect" && _this.drawFlag)) {
if(svgRect) { if (svgRect) {
var width = Math.abs(currX-startCoords[0]); var width = Math.abs(currX - startCoords[0]);
var height = Math.abs(currY-startCoords[1]); var height = Math.abs(currY - startCoords[1]);
if(shiftPressed) { if (shiftPressed) {
height=width; height = width;
var x = currX<startCoords[0] ? startCoords[0]-width : startCoords[0]; var x = currX < startCoords[0] ? startCoords[0] - width : startCoords[0];
var y = currY<startCoords[1] ? startCoords[1]-width : startCoords[1]; var y = currY < startCoords[1] ? startCoords[1] - width : startCoords[1];
svgRect.setAttribute('x', x); svgRect.setAttribute('x', x);
svgRect.setAttribute('y', y); svgRect.setAttribute('y', y);
} else { } else {
var x = currX<startCoords[0] ? currX : startCoords[0]; var x = currX < startCoords[0] ? currX : startCoords[0];
var y = currY<startCoords[1] ? currY : startCoords[1]; var y = currY < startCoords[1] ? currY : startCoords[1];
svgRect.setAttribute('x', x); svgRect.setAttribute('x', x);
svgRect.setAttribute('y', y); svgRect.setAttribute('y', y);
} }
svgRect.setAttribute('width',width); svgRect.setAttribute('width', width);
svgRect.setAttribute('height',height); svgRect.setAttribute('height', height);
} }
} else if(_this.tool==="circle") { } else if (_this.tool === "circle") {
var a = currX - startCoords[0]; var a = currX - startCoords[0];
var b = currY - startCoords[1]; var b = currY - startCoords[1];
var r = Math.sqrt( a*a + b*b ); var r = Math.sqrt(a * a + b * b);
if(svgCirle) { if (svgCirle) {
svgCirle.setAttribute('r', r); svgCirle.setAttribute('r', r);
} }
} }
}); });
_this.sendFunction({"t":"cursor","event":"move","d":[currX, currY], "username":_this.settings.username}); _this.sendFunction({ "t": "cursor", "event": "move", "d": [currX, currY], "username": _this.settings.username });
}); });
$(_this.mouseOverlay).on("mouseup touchend touchcancel", function(e) { $(_this.mouseOverlay).on("mouseup touchend touchcancel", function (e) {
if(_this.imgDragActive) { if (_this.imgDragActive) {
return; return;
} }
_this.drawFlag=false; _this.drawFlag = false;
_this.drawId++; _this.drawId++;
_this.ctx.globalCompositeOperation = _this.oldGCO; _this.ctx.globalCompositeOperation = _this.oldGCO;
var currX = (e.offsetX || e.pageX - $(e.target).offset().left); var currX = (e.offsetX || e.pageX - $(e.target).offset().left);
var currY = (e.offsetY || e.pageY - $(e.target).offset().top); var currY = (e.offsetY || e.pageY - $(e.target).offset().top);
if((!currX || !currY) && e.touches[0]) { if ((!currX || !currY) && e.touches[0]) {
currX = latestTouchCoods[0]; currX = latestTouchCoods[0];
currY = latestTouchCoods[1]; currY = latestTouchCoods[1];
_this.sendFunction({"t":"cursor","event":"out", "username":_this.settings.username}); _this.sendFunction({ "t": "cursor", "event": "out", "username": _this.settings.username });
} }
if(_this.tool==="line") { if (_this.tool === "line") {
if(shiftPressed) { if (shiftPressed) {
var angs = getRoundedAngles(currX, currY); var angs = getRoundedAngles(currX, currY);
currX = angs.x; currX = angs.x;
currY = angs.y; currY = angs.y;
} }
_this.drawPenLine(currX, currY, startCoords[0], startCoords[1], _this.drawcolor, _this.thickness); _this.drawPenLine(currX, currY, startCoords[0], startCoords[1], _this.drawcolor, _this.thickness);
_this.sendFunction({"t":_this.tool,"d":[currX, currY, startCoords[0], startCoords[1]], "c":_this.drawcolor, "th":_this.thickness}); _this.sendFunction({ "t": _this.tool, "d": [currX, currY, startCoords[0], startCoords[1]], "c": _this.drawcolor, "th": _this.thickness });
_this.svgContainer.find("line").remove(); _this.svgContainer.find("line").remove();
} else if(_this.tool==="rect") { } else if (_this.tool === "rect") {
if(shiftPressed) { if (shiftPressed) {
if((currY-startCoords[1])*(currX-startCoords[0])>0) { if ((currY - startCoords[1]) * (currX - startCoords[0]) > 0) {
currY = startCoords[1]+(currX-startCoords[0]); currY = startCoords[1] + (currX - startCoords[0]);
} else { } else {
currY = startCoords[1]-(currX-startCoords[0]); currY = startCoords[1] - (currX - startCoords[0]);
} }
} }
_this.drawRec(startCoords[0], startCoords[1], currX, currY, _this.drawcolor, _this.thickness); _this.drawRec(startCoords[0], startCoords[1], currX, currY, _this.drawcolor, _this.thickness);
_this.sendFunction({"t":_this.tool,"d":[startCoords[0], startCoords[1], currX, currY], "c":_this.drawcolor, "th":_this.thickness}); _this.sendFunction({ "t": _this.tool, "d": [startCoords[0], startCoords[1], currX, currY], "c": _this.drawcolor, "th": _this.thickness });
_this.svgContainer.find("rect").remove(); _this.svgContainer.find("rect").remove();
} else if(_this.tool==="circle") { } else if (_this.tool === "circle") {
var a = currX - startCoords[0]; var a = currX - startCoords[0];
var b = currY - startCoords[1]; var b = currY - startCoords[1];
var r = Math.sqrt( a*a + b*b ); var r = Math.sqrt(a * a + b * b);
_this.drawCircle(startCoords[0], startCoords[1], r, _this.drawcolor, _this.thickness); _this.drawCircle(startCoords[0], startCoords[1], r, _this.drawcolor, _this.thickness);
_this.sendFunction({"t":_this.tool,"d":[startCoords[0], startCoords[1], r], "c":_this.drawcolor, "th":_this.thickness}); _this.sendFunction({ "t": _this.tool, "d": [startCoords[0], startCoords[1], r], "c": _this.drawcolor, "th": _this.thickness });
_this.svgContainer.find("circle").remove(); _this.svgContainer.find("circle").remove();
} else if(_this.tool==="recSelect") { } else if (_this.tool === "recSelect") {
_this.imgDragActive = true; _this.imgDragActive = true;
if(shiftPressed) { if (shiftPressed) {
if((currY-startCoords[1])*(currX-startCoords[0])>0) { if ((currY - startCoords[1]) * (currX - startCoords[0]) > 0) {
currY = startCoords[1]+(currX-startCoords[0]); currY = startCoords[1] + (currX - startCoords[0]);
} else { } else {
currY = startCoords[1]-(currX-startCoords[0]); currY = startCoords[1] - (currX - startCoords[0]);
} }
} }
var width = Math.abs(startCoords[0] - currX); var width = Math.abs(startCoords[0] - currX);
var height = Math.abs(startCoords[1] - currY); var height = Math.abs(startCoords[1] - currY);
var left = startCoords[0]< currX ? startCoords[0] : currX; var left = startCoords[0] < currX ? startCoords[0] : currX;
var top = startCoords[1]< currY ? startCoords[1] : currY; var top = startCoords[1] < currY ? startCoords[1] : currY;
_this.mouseOverlay.css({"cursor":"default"}); _this.mouseOverlay.css({ "cursor": "default" });
var imgDiv = $('<div style="position:absolute; left:'+left+'px; top:'+top+'px; width:'+width+'px; border: 2px dotted gray; overflow: hidden; height:'+height+'px;" cursor:move;">'+ var imgDiv = $('<div style="position:absolute; left:' + left + 'px; top:' + top + 'px; width:' + width + 'px; border: 2px dotted gray; overflow: hidden; height:' + height + 'px;" cursor:move;">' +
'<canvas style="cursor:move; position:absolute; top:0px; left:0px;" width="'+width+'" height="'+height+'"/>'+ '<canvas style="cursor:move; position:absolute; top:0px; left:0px;" width="' + width + '" height="' + height + '"/>' +
'<div style="position:absolute; right:5px; top:3px;">'+ '<div style="position:absolute; right:5px; top:3px;">' +
'<button draw="1" style="margin: 0px 0px; background: #03a9f4; padding: 5px; margin-top: 3px; color: white;" class="addToCanvasBtn btn btn-default">Drop</button> '+ '<button draw="1" style="margin: 0px 0px; background: #03a9f4; padding: 5px; margin-top: 3px; color: white;" class="addToCanvasBtn btn btn-default">Drop</button> ' +
'<button style="margin: 0px 0px; background: #03a9f4; padding: 5px; margin-top: 3px; color: white;" class="xCanvasBtn btn btn-default">x</button>'+ '<button style="margin: 0px 0px; background: #03a9f4; padding: 5px; margin-top: 3px; color: white;" class="xCanvasBtn btn btn-default">x</button>' +
'</div>'+ '</div>' +
'</div>'); '</div>');
var dragCanvas = $(imgDiv).find("canvas"); var dragCanvas = $(imgDiv).find("canvas");
var dragOutOverlay = $('<div class="dragOutOverlay" style="position:absolute; left:'+left+'px; top:'+top+'px; width:'+width+'px; height:'+height+'px; background:white;"></div>'); var dragOutOverlay = $('<div class="dragOutOverlay" style="position:absolute; left:' + left + 'px; top:' + top + 'px; width:' + width + 'px; height:' + height + 'px; background:white;"></div>');
_this.mouseOverlay.append(dragOutOverlay); _this.mouseOverlay.append(dragOutOverlay);
_this.mouseOverlay.append(imgDiv); _this.mouseOverlay.append(imgDiv);
var destCanvasContext = dragCanvas[0].getContext('2d'); var destCanvasContext = dragCanvas[0].getContext('2d');
destCanvasContext.drawImage(_this.canvas,left,top,width,height,0,0,width,height); destCanvasContext.drawImage(_this.canvas, left, top, width, height, 0, 0, width, height);
imgDiv.find(".xCanvasBtn").click(function() { imgDiv.find(".xCanvasBtn").click(function () {
_this.imgDragActive = false; _this.imgDragActive = false;
if(_this.tool==="pen") if (_this.tool === "pen") {
_this.mouseOverlay.css({"cursor":"none"}); _this.mouseOverlay.css({ "cursor": "none" });
else } else {
_this.mouseOverlay.css({"cursor":"crosshair"}); _this.mouseOverlay.css({ "cursor": "crosshair" });
}
imgDiv.remove(); imgDiv.remove();
dragOutOverlay.remove(); dragOutOverlay.remove();
}); });
imgDiv.find(".addToCanvasBtn").click(function() { imgDiv.find(".addToCanvasBtn").click(function () {
_this.imgDragActive = false; _this.imgDragActive = false;
if(_this.tool==="pen") if (_this.tool === "pen") {
_this.mouseOverlay.css({"cursor":"none"}); _this.mouseOverlay.css({ "cursor": "none" });
else } else {
_this.mouseOverlay.css({"cursor":"crosshair"}); _this.mouseOverlay.css({ "cursor": "crosshair" });
}
var widthT = imgDiv.width(); var widthT = imgDiv.width();
var heightT = imgDiv.height(); var heightT = imgDiv.height();
var p = imgDiv.position(); var p = imgDiv.position();
var leftT = Math.round(p.left*100)/100; var leftT = Math.round(p.left * 100) / 100;
var topT = Math.round(p.top*100)/100; var topT = Math.round(p.top * 100) / 100;
//xf, yf, xt, yt, width, height //xf, yf, xt, yt, width, height
_this.drawId++; _this.drawId++;
_this.sendFunction({"t":_this.tool,"d":[left, top,leftT,topT,width,height]}); _this.sendFunction({ "t": _this.tool, "d": [left, top, leftT, topT, width, height] });
_this.dragCanvasRectContent(left, top,leftT,topT,width,height); _this.dragCanvasRectContent(left, top, leftT, topT, width, height);
imgDiv.remove(); imgDiv.remove();
dragOutOverlay.remove(); dragOutOverlay.remove();
}); });
@ -302,33 +303,33 @@ var whiteboard = {
} }
}); });
$(_this.mouseOverlay).on("mouseout", function(e) { $(_this.mouseOverlay).on("mouseout", function (e) {
if(_this.imgDragActive) { if (_this.imgDragActive) {
return; return;
} }
_this.drawFlag=false; _this.drawFlag = false;
_this.mouseover = false; _this.mouseover = false;
_this.ctx.globalCompositeOperation = _this.oldGCO; _this.ctx.globalCompositeOperation = _this.oldGCO;
_this.ownCursor.remove(); _this.ownCursor.remove();
_this.svgContainer.find("line").remove(); _this.svgContainer.find("line").remove();
_this.svgContainer.find("rect").remove(); _this.svgContainer.find("rect").remove();
_this.svgContainer.find("circle").remove(); _this.svgContainer.find("circle").remove();
_this.sendFunction({"t":"cursor","event":"out"}); _this.sendFunction({ "t": "cursor", "event": "out" });
}); });
$(_this.mouseOverlay).on("mouseover", function(e) { $(_this.mouseOverlay).on("mouseover", function (e) {
if(_this.imgDragActive) { if (_this.imgDragActive) {
return; return;
} }
if(!_this.mouseover) { if (!_this.mouseover) {
var color = _this.drawcolor; var color = _this.drawcolor;
var widthHeight = _this.thickness; var widthHeight = _this.thickness;
if(_this.tool==="eraser") { if (_this.tool === "eraser") {
color = "#00000000"; color = "#00000000";
widthHeight = widthHeight * 2; widthHeight = widthHeight * 2;
} }
if(_this.tool==="eraser" || _this.tool==="pen") { if (_this.tool === "eraser" || _this.tool === "pen") {
_this.ownCursor = $('<div id="ownCursor" style="background:'+color+'; border:1px solid gray; position:absolute; width:'+widthHeight+'px; height:'+widthHeight+'px; border-radius:50%;"></div>'); _this.ownCursor = $('<div id="ownCursor" style="background:' + color + '; border:1px solid gray; position:absolute; width:' + widthHeight + 'px; height:' + widthHeight + 'px; border-radius:50%;"></div>');
_this.cursorContainer.append(_this.ownCursor); _this.cursorContainer.append(_this.ownCursor);
} }
} }
@ -338,86 +339,86 @@ var whiteboard = {
var strgPressed = false; var strgPressed = false;
var zPressed = false; var zPressed = false;
var shiftPressed = false; var shiftPressed = false;
$(document).on("keydown", function(e) { $(document).on("keydown", function (e) {
if(e.which == 17) { if (e.which == 17) {
strgPressed = true; strgPressed = true;
} else if(e.which == 90) { } else if (e.which == 90) {
if(strgPressed && !zPressed) { if (strgPressed && !zPressed) {
_this.undoWhiteboardClick(); _this.undoWhiteboardClick();
} }
zPressed = true; zPressed = true;
} else if(e.which == 16) { } else if (e.which == 16) {
shiftPressed = true; shiftPressed = true;
} else if(e.which == 27) { //Esc } else if (e.which == 27) { //Esc
if(!_this.drawFlag) if (!_this.drawFlag)
_this.svgContainer.empty(); _this.svgContainer.empty();
_this.mouseOverlay.find(".xCanvasBtn").click(); //Remove all current drops _this.mouseOverlay.find(".xCanvasBtn").click(); //Remove all current drops
} else if(e.which == 46) { //Remove / Entf } else if (e.which == 46) { //Remove / Entf
$.each(_this.mouseOverlay.find(".dragOutOverlay"), function() { $.each(_this.mouseOverlay.find(".dragOutOverlay"), function () {
var width = $(this).width(); var width = $(this).width();
var height = $(this).height(); var height = $(this).height();
var p = $(this).position(); var p = $(this).position();
var left = Math.round(p.left*100)/100; var left = Math.round(p.left * 100) / 100;
var top = Math.round(p.top*100)/100; var top = Math.round(p.top * 100) / 100;
_this.drawId++; _this.drawId++;
_this.sendFunction({"t":"eraseRec","d":[left, top,width,height]}); _this.sendFunction({ "t": "eraseRec", "d": [left, top, width, height] });
_this.eraseRec(left, top, width, height); _this.eraseRec(left, top, width, height);
}); });
_this.mouseOverlay.find(".xCanvasBtn").click(); //Remove all current drops _this.mouseOverlay.find(".xCanvasBtn").click(); //Remove all current drops
} }
//console.log(e.which); //console.log(e.which);
}); });
$(document).on("keyup", function(e) { $(document).on("keyup", function (e) {
if(e.which == 17) { if (e.which == 17) {
strgPressed = false; strgPressed = false;
} else if(e.which == 90) { } else if (e.which == 90) {
zPressed = false; zPressed = false;
} else if(e.which == 16) { } else if (e.which == 16) {
shiftPressed = false; shiftPressed = false;
} }
}); });
function getRoundedAngles(currX, currY) { //For drawing lines at 0,45,90° .... function getRoundedAngles(currX, currY) { //For drawing lines at 0,45,90° ....
var x = currX-startCoords[0]; var x = currX - startCoords[0];
var y = currY-startCoords[1]; var y = currY - startCoords[1];
var angle = Math.atan2(x, y)* (180 / Math.PI); var angle = Math.atan2(x, y) * (180 / Math.PI);
var angle45 = Math.round(angle/45)*45; var angle45 = Math.round(angle / 45) * 45;
if(angle45%90==0) { if (angle45 % 90 == 0) {
if(Math.abs(currX-startCoords[0])>Math.abs(currY-startCoords[1])) { if (Math.abs(currX - startCoords[0]) > Math.abs(currY - startCoords[1])) {
currY = startCoords[1] currY = startCoords[1]
} else { } else {
currX = startCoords[0] currX = startCoords[0]
} }
} else { } else {
if((currY-startCoords[1])*(currX-startCoords[0])>0) { if ((currY - startCoords[1]) * (currX - startCoords[0]) > 0) {
currX = startCoords[0]+(currY-startCoords[1]); currX = startCoords[0] + (currY - startCoords[1]);
} else { } else {
currX = startCoords[0]-(currY-startCoords[1]); currX = startCoords[0] - (currY - startCoords[1]);
} }
} }
return { "x": currX, "y" : currY}; return { "x": currX, "y": currY };
} }
}, },
dragCanvasRectContent : function(xf, yf, xt, yt, width, height) { dragCanvasRectContent: function (xf, yf, xt, yt, width, height) {
var tempCanvas = document.createElement('canvas'); var tempCanvas = document.createElement('canvas');
tempCanvas.width = width; tempCanvas.width = width;
tempCanvas.height = height; tempCanvas.height = height;
var tempCanvasContext = tempCanvas.getContext('2d'); var tempCanvasContext = tempCanvas.getContext('2d');
tempCanvasContext.drawImage(this.canvas,xf,yf,width,height,0,0,width,height); tempCanvasContext.drawImage(this.canvas, xf, yf, width, height, 0, 0, width, height);
this.eraseRec(xf,yf,width,height); this.eraseRec(xf, yf, width, height);
this.ctx.drawImage(tempCanvas,xt,yt); this.ctx.drawImage(tempCanvas, xt, yt);
}, },
eraseRec : function(fromX, fromY, width, height) { eraseRec: function (fromX, fromY, width, height) {
var _this = this; var _this = this;
_this.ctx.beginPath(); _this.ctx.beginPath();
_this.ctx.rect(fromX,fromY,width,height); _this.ctx.rect(fromX, fromY, width, height);
_this.ctx.fillStyle = "rgba(0,0,0,1)"; _this.ctx.fillStyle = "rgba(0,0,0,1)";
_this.ctx.globalCompositeOperation = "destination-out"; _this.ctx.globalCompositeOperation = "destination-out";
_this.ctx.fill(); _this.ctx.fill();
_this.ctx.closePath(); _this.ctx.closePath();
_this.ctx.globalCompositeOperation = _this.oldGCO; _this.ctx.globalCompositeOperation = _this.oldGCO;
}, },
drawPenLine : function(fromX, fromY, toX, toY, color, thickness) { drawPenLine: function (fromX, fromY, toX, toY, color, thickness) {
var _this = this; var _this = this;
_this.ctx.beginPath(); _this.ctx.beginPath();
_this.ctx.moveTo(fromX, fromY); _this.ctx.moveTo(fromX, fromY);
@ -428,32 +429,32 @@ var whiteboard = {
_this.ctx.stroke(); _this.ctx.stroke();
_this.ctx.closePath(); _this.ctx.closePath();
}, },
drawEraserLine : function(fromX, fromY, toX, toY, thickness) { drawEraserLine: function (fromX, fromY, toX, toY, thickness) {
var _this = this; var _this = this;
_this.ctx.beginPath(); _this.ctx.beginPath();
_this.ctx.moveTo(fromX, fromY); _this.ctx.moveTo(fromX, fromY);
_this.ctx.lineTo(toX, toY); _this.ctx.lineTo(toX, toY);
_this.ctx.strokeStyle = "rgba(0,0,0,1)"; _this.ctx.strokeStyle = "rgba(0,0,0,1)";
_this.ctx.lineWidth = thickness*2; _this.ctx.lineWidth = thickness * 2;
_this.ctx.lineCap = _this.lineCap; _this.ctx.lineCap = _this.lineCap;
_this.ctx.globalCompositeOperation = "destination-out"; _this.ctx.globalCompositeOperation = "destination-out";
_this.ctx.stroke(); _this.ctx.stroke();
_this.ctx.closePath(); _this.ctx.closePath();
_this.ctx.globalCompositeOperation = _this.oldGCO; _this.ctx.globalCompositeOperation = _this.oldGCO;
}, },
drawRec : function(fromX, fromY, toX, toY, color, thickness) { drawRec: function (fromX, fromY, toX, toY, color, thickness) {
var _this = this; var _this = this;
toX = toX - fromX; toX = toX - fromX;
toY = toY - fromY; toY = toY - fromY;
_this.ctx.beginPath(); _this.ctx.beginPath();
_this.ctx.rect(fromX,fromY,toX,toY); _this.ctx.rect(fromX, fromY, toX, toY);
_this.ctx.strokeStyle = color; _this.ctx.strokeStyle = color;
_this.ctx.lineWidth = thickness; _this.ctx.lineWidth = thickness;
_this.ctx.lineCap = _this.lineCap; _this.ctx.lineCap = _this.lineCap;
_this.ctx.stroke(); _this.ctx.stroke();
_this.ctx.closePath(); _this.ctx.closePath();
}, },
drawCircle : function(fromX, fromY, radius, color, thickness) { drawCircle: function (fromX, fromY, radius, color, thickness) {
var _this = this; var _this = this;
_this.ctx.beginPath(); _this.ctx.beginPath();
_this.ctx.arc(fromX, fromY, radius, 0, 2 * Math.PI, false); _this.ctx.arc(fromX, fromY, radius, 0, 2 * Math.PI, false);
@ -461,59 +462,59 @@ var whiteboard = {
_this.ctx.strokeStyle = color; _this.ctx.strokeStyle = color;
_this.ctx.stroke(); _this.ctx.stroke();
}, },
clearWhiteboard : function() { clearWhiteboard: function () {
var _this = this; var _this = this;
_this.canvas.height = _this.canvas.height; _this.canvas.height = _this.canvas.height;
_this.imgContainer.empty(); _this.imgContainer.empty();
_this.sendFunction({"t":"clear"}); _this.sendFunction({ "t": "clear" });
_this.drawBuffer = []; _this.drawBuffer = [];
_this.drawId = 0; _this.drawId = 0;
}, },
addImgToCanvasByUrl : function(url) { addImgToCanvasByUrl: function (url) {
var _this = this; var _this = this;
_this.imgDragActive = true; _this.imgDragActive = true;
_this.mouseOverlay.css({"cursor":"default"}); _this.mouseOverlay.css({ "cursor": "default" });
var imgDiv = $('<div style="border: 2px dashed gray; position:absolute; left:200px; top:200px; min-width:160px; min-height:100px; cursor:move;">'+ var imgDiv = $('<div style="border: 2px dashed gray; position:absolute; left:200px; top:200px; min-width:160px; min-height:100px; cursor:move;">' +
'<img style="width:100%; height:100%;" src="'+url+'">'+ '<img style="width:100%; height:100%;" src="' + url + '">' +
'<div style="position:absolute; right:5px; top:3px;">'+ '<div style="position:absolute; right:5px; top:3px;">' +
'<button draw="1" style="margin: 0px 0px; background: #03a9f4; padding: 5px; margin-top: 3px; color: white;" class="addToCanvasBtn btn btn-default">Draw to canvas</button> '+ '<button draw="1" style="margin: 0px 0px; background: #03a9f4; padding: 5px; margin-top: 3px; color: white;" class="addToCanvasBtn btn btn-default">Draw to canvas</button> ' +
'<button draw="0" style="margin: 0px 0px; background: #03a9f4; padding: 5px; margin-top: 3px; color: white;" class="addToCanvasBtn btn btn-default">Add to background</button> '+ '<button draw="0" style="margin: 0px 0px; background: #03a9f4; padding: 5px; margin-top: 3px; color: white;" class="addToCanvasBtn btn btn-default">Add to background</button> ' +
'<button style="margin: 0px 0px; background: #03a9f4; padding: 5px; margin-top: 3px; color: white;" class="xCanvasBtn btn btn-default">x</button>'+ '<button style="margin: 0px 0px; background: #03a9f4; padding: 5px; margin-top: 3px; color: white;" class="xCanvasBtn btn btn-default">x</button>' +
'</div>'+ '</div>' +
'<i style="position:absolute; bottom: -4px; right: 2px; font-size: 2em; color: gray; transform: rotate(-45deg);" class="fas fa-sort-down" aria-hidden="true"></i>'+ '<i style="position:absolute; bottom: -4px; right: 2px; font-size: 2em; color: gray; transform: rotate(-45deg);" class="fas fa-sort-down" aria-hidden="true"></i>' +
'</div>'); '</div>');
imgDiv.find(".xCanvasBtn").click(function() { imgDiv.find(".xCanvasBtn").click(function () {
_this.imgDragActive = false; _this.imgDragActive = false;
if(_this.tool==="pen") { if (_this.tool === "pen") {
_this.mouseOverlay.css({"cursor":"none"}); _this.mouseOverlay.css({ "cursor": "none" });
} else if(_this.tool==="mouse") { } else if (_this.tool === "mouse") {
_this.mouseOverlay.css({"cursor":"auto"}); _this.mouseOverlay.css({ "cursor": "auto" });
} else { } else {
_this.mouseOverlay.css({"cursor":"crosshair"}); _this.mouseOverlay.css({ "cursor": "crosshair" });
} }
imgDiv.remove(); imgDiv.remove();
}); });
imgDiv.find(".addToCanvasBtn").click(function() { imgDiv.find(".addToCanvasBtn").click(function () {
var draw = $(this).attr("draw"); var draw = $(this).attr("draw");
_this.imgDragActive = false; _this.imgDragActive = false;
if(_this.tool==="pen") { if (_this.tool === "pen") {
_this.mouseOverlay.css({"cursor":"none"}); _this.mouseOverlay.css({ "cursor": "none" });
} else if(_this.tool==="mouse") { } else if (_this.tool === "mouse") {
_this.mouseOverlay.css({"cursor":"auto"}); _this.mouseOverlay.css({ "cursor": "auto" });
} else { } else {
_this.mouseOverlay.css({"cursor":"crosshair"}); _this.mouseOverlay.css({ "cursor": "crosshair" });
} }
var width = imgDiv.width(); var width = imgDiv.width();
var height = imgDiv.height(); var height = imgDiv.height();
var p = imgDiv.position(); var p = imgDiv.position();
var left = Math.round(p.left*100)/100; var left = Math.round(p.left * 100) / 100;
var top = Math.round(p.top*100)/100; var top = Math.round(p.top * 100) / 100;
if(draw=="1") { //draw image to canvas if (draw == "1") { //draw image to canvas
_this.drawImgToCanvas(url,width,height,left,top); _this.drawImgToCanvas(url, width, height, left, top);
} else { //Add image to background } else { //Add image to background
_this.drawImgToBackground(url,width,height,left,top); _this.drawImgToBackground(url, width, height, left, top);
} }
_this.sendFunction({"t":"addImgBG", "draw":draw, "url":url, "d":[width,height,left,top]}); _this.sendFunction({ "t": "addImgBG", "draw": draw, "url": url, "d": [width, height, left, top] });
_this.drawId++; _this.drawId++;
imgDiv.remove(); imgDiv.remove();
}); });
@ -521,30 +522,30 @@ var whiteboard = {
imgDiv.draggable(); imgDiv.draggable();
imgDiv.resizable(); imgDiv.resizable();
}, },
drawImgToBackground(url,width,height,left,top) { drawImgToBackground(url, width, height, left, top) {
this.imgContainer.append('<img crossorigin="anonymous" style="width:'+width+'px; height:'+height+'px; position:absolute; top:'+top+'px; left:'+left+'px;" src="'+url+'">') this.imgContainer.append('<img crossorigin="anonymous" style="width:' + width + 'px; height:' + height + 'px; position:absolute; top:' + top + 'px; left:' + left + 'px;" src="' + url + '">')
}, },
drawImgToCanvas(url,width,height,left,top, doneCallback) { drawImgToCanvas(url, width, height, left, top, doneCallback) {
var _this = this; var _this = this;
var img = document.createElement('img'); var img = document.createElement('img');
img.onload=function(){ img.onload = function () {
_this.ctx.drawImage(img,left,top,width,height); _this.ctx.drawImage(img, left, top, width, height);
if(doneCallback) { if (doneCallback) {
doneCallback(); doneCallback();
} }
} }
img.src = url; img.src = url;
}, },
undoWhiteboard : function(username) { //Not call this directly because you will get out of sync whit others... undoWhiteboard: function (username) { //Not call this directly because you will get out of sync whit others...
var _this = this; var _this = this;
if(!username) { if (!username) {
username = _this.settings.username; username = _this.settings.username;
} }
for(var i=_this.drawBuffer.length-1;i>=0;i--){ for (var i = _this.drawBuffer.length - 1; i >= 0; i--) {
if(_this.drawBuffer[i]["username"]==username) { if (_this.drawBuffer[i]["username"] == username) {
var drawId = _this.drawBuffer[i]["drawId"]; var drawId = _this.drawBuffer[i]["drawId"];
for(var i=_this.drawBuffer.length-1;i>=0;i--){ for (var i = _this.drawBuffer.length - 1; i >= 0; i--) {
if(_this.drawBuffer[i]["drawId"]==drawId && _this.drawBuffer[i]["username"]==username) { if (_this.drawBuffer[i]["drawId"] == drawId && _this.drawBuffer[i]["username"] == username) {
_this.drawBuffer.splice(i, 1); _this.drawBuffer.splice(i, 1);
} }
} }
@ -554,81 +555,81 @@ var whiteboard = {
_this.canvas.height = _this.canvas.height; _this.canvas.height = _this.canvas.height;
_this.imgContainer.empty(); _this.imgContainer.empty();
console.log(_this.drawBuffer) console.log(_this.drawBuffer)
_this.loadDataInSteps(_this.drawBuffer,false, function(stepData) { _this.loadDataInSteps(_this.drawBuffer, false, function (stepData) {
//Nothing to do //Nothing to do
}); });
}, },
undoWhiteboardClick : function() { undoWhiteboardClick: function () {
this.sendFunction({"t":"undo"}); this.sendFunction({ "t": "undo" });
this.undoWhiteboard(); this.undoWhiteboard();
}, },
setTool : function(tool) { setTool: function (tool) {
this.tool = tool; this.tool = tool;
if(tool==="pen" || tool==="eraser") { if (tool === "pen" || tool === "eraser") {
this.mouseOverlay.css({"cursor":"none"}); this.mouseOverlay.css({ "cursor": "none" });
} else if(tool==="mouse"){ } else if (tool === "mouse") {
this.mouseOverlay.css({"cursor":"default"}); this.mouseOverlay.css({ "cursor": "default" });
} else { } else {
this.mouseOverlay.css({"cursor":"crosshair"}); this.mouseOverlay.css({ "cursor": "crosshair" });
} }
this.mouseOverlay.find(".xCanvasBtn").click(); this.mouseOverlay.find(".xCanvasBtn").click();
}, },
handleEventsAndData : function(content, isNewData, doneCallback) { handleEventsAndData: function (content, isNewData, doneCallback) {
var _this = this; var _this = this;
var tool = content["t"]; var tool = content["t"];
var data = content["d"]; var data = content["d"];
var color = content["c"]; var color = content["c"];
var username = content["username"]; var username = content["username"];
var thickness = content["th"]; var thickness = content["th"];
window.requestAnimationFrame(function() { window.requestAnimationFrame(function () {
if(tool==="line" || tool==="pen") { if (tool === "line" || tool === "pen") {
_this.drawPenLine(data[0], data[1], data[2], data[3], color, thickness); _this.drawPenLine(data[0], data[1], data[2], data[3], color, thickness);
} else if(tool==="rect"){ } else if (tool === "rect") {
_this.drawRec(data[0], data[1], data[2], data[3], color, thickness); _this.drawRec(data[0], data[1], data[2], data[3], color, thickness);
} else if(tool==="circle"){ } else if (tool === "circle") {
_this.drawCircle(data[0], data[1], data[2], color, thickness); _this.drawCircle(data[0], data[1], data[2], color, thickness);
} else if(tool==="eraser"){ } else if (tool === "eraser") {
_this.drawEraserLine(data[0], data[1], data[2], data[3], thickness); _this.drawEraserLine(data[0], data[1], data[2], data[3], thickness);
} else if(tool==="eraseRec"){ } else if (tool === "eraseRec") {
_this.eraseRec(data[0], data[1],data[2],data[3]); _this.eraseRec(data[0], data[1], data[2], data[3]);
} else if(tool==="recSelect"){ } else if (tool === "recSelect") {
_this.dragCanvasRectContent(data[0], data[1],data[2],data[3],data[4],data[5]); _this.dragCanvasRectContent(data[0], data[1], data[2], data[3], data[4], data[5]);
} else if(tool==="addImgBG") { } else if (tool === "addImgBG") {
if(content["draw"]=="1") { if (content["draw"] == "1") {
_this.drawImgToCanvas(content["url"],data[0],data[1],data[2],data[3], doneCallback) _this.drawImgToCanvas(content["url"], data[0], data[1], data[2], data[3], doneCallback)
} else { } else {
_this.drawImgToBackground(content["url"],data[0],data[1],data[2],data[3]); _this.drawImgToBackground(content["url"], data[0], data[1], data[2], data[3]);
} }
} else if(tool==="clear") { } else if (tool === "clear") {
_this.canvas.height = _this.canvas.height; _this.canvas.height = _this.canvas.height;
this.imgContainer.empty(); this.imgContainer.empty();
this.drawBuffer = []; this.drawBuffer = [];
this.drawId = 0; this.drawId = 0;
} else if(tool==="cursor" && _this.settings) { } else if (tool === "cursor" && _this.settings) {
if(content["event"]==="move") { if (content["event"] === "move") {
if(_this.cursorContainer.find("."+content["username"]).length>=1) { if (_this.cursorContainer.find("." + content["username"]).length >= 1) {
_this.cursorContainer.find("."+content["username"]).css({"left":data[0]+"px","top":data[1]+"px" }); _this.cursorContainer.find("." + content["username"]).css({ "left": data[0] + "px", "top": data[1] + "px" });
} else { } else {
_this.cursorContainer.append('<div style="font-size:0.8em; padding-left:2px; padding-right:2px; background:gray; color:white; border-radius:3px; position:absolute; left:'+data[0]+'; top:'+data[1]+';" class="userbadge '+content["username"]+'">'+ _this.cursorContainer.append('<div style="font-size:0.8em; padding-left:2px; padding-right:2px; background:gray; color:white; border-radius:3px; position:absolute; left:' + data[0] + '; top:' + data[1] + ';" class="userbadge ' + content["username"] + '">' +
'<div style="width:4px; height:4px; background:gray; position:absolute; top:-2px; left:-2px; border-radius:50%;"></div>'+ '<div style="width:4px; height:4px; background:gray; position:absolute; top:-2px; left:-2px; border-radius:50%;"></div>' +
content["username"]+'</div>'); content["username"] + '</div>');
} }
} else { } else {
_this.cursorContainer.find("."+content["username"]).remove(); _this.cursorContainer.find("." + content["username"]).remove();
} }
} else if(tool==="undo") { } else if (tool === "undo") {
_this.undoWhiteboard(username); _this.undoWhiteboard(username);
} }
}); });
if(isNewData && (tool==="line" || tool==="pen" || tool==="rect" || tool==="circle" || tool==="eraser" || tool==="addImgBG" || tool==="recSelect" || tool==="eraseRec")) { if (isNewData && (tool === "line" || tool === "pen" || tool === "rect" || tool === "circle" || tool === "eraser" || tool === "addImgBG" || tool === "recSelect" || tool === "eraseRec")) {
content["drawId"] = content["drawId"] ? content["drawId"] : _this.drawId; content["drawId"] = content["drawId"] ? content["drawId"] : _this.drawId;
content["username"] = content["username"] ? content["username"] : _this.settings.username; content["username"] = content["username"] ? content["username"] : _this.settings.username;
_this.drawBuffer.push(content); _this.drawBuffer.push(content);
} }
}, },
userLeftWhiteboard(username) { userLeftWhiteboard(username) {
this.cursorContainer.find("."+username).remove(); this.cursorContainer.find("." + username).remove();
}, },
refreshUserBadges() { refreshUserBadges() {
this.cursorContainer.find(".userbadge").remove(); this.cursorContainer.find(".userbadge").remove();
@ -642,13 +643,13 @@ var whiteboard = {
copyCanvas.height = height; copyCanvas.height = height;
var ctx = copyCanvas.getContext("2d"); var ctx = copyCanvas.getContext("2d");
$.each(_this.imgContainer.find("img"), function() { $.each(_this.imgContainer.find("img"), function () {
var width = $(this).width(); var width = $(this).width();
var height = $(this).height(); var height = $(this).height();
var p = $(this).position(); var p = $(this).position();
var left = Math.round(p.left*100)/100; var left = Math.round(p.left * 100) / 100;
var top = Math.round(p.top*100)/100; var top = Math.round(p.top * 100) / 100;
ctx.drawImage(this,left,top,width,height); ctx.drawImage(this, left, top, width, height);
}); });
var destCtx = copyCanvas.getContext('2d'); var destCtx = copyCanvas.getContext('2d');
@ -658,7 +659,7 @@ var whiteboard = {
}, },
getImageDataJson() { getImageDataJson() {
var sendObj = []; var sendObj = [];
for(var i=0;i<this.drawBuffer.length;i++) { for (var i = 0; i < this.drawBuffer.length; i++) {
sendObj.push(JSON.parse(JSON.stringify(this.drawBuffer[i]))); sendObj.push(JSON.parse(JSON.stringify(this.drawBuffer[i])));
delete sendObj[i]["username"]; delete sendObj[i]["username"];
delete sendObj[i]["wid"]; delete sendObj[i]["wid"];
@ -666,22 +667,22 @@ var whiteboard = {
} }
return JSON.stringify(sendObj); return JSON.stringify(sendObj);
}, },
loadData : function(content) { loadData: function (content) {
var _this = this; var _this = this;
_this.loadDataInSteps(content, true, function(stepData) { _this.loadDataInSteps(content, true, function (stepData) {
if(stepData["username"]==_this.settings.username && _this.drawId < stepData["drawId"]) { if (stepData["username"] == _this.settings.username && _this.drawId < stepData["drawId"]) {
_this.drawId = stepData["drawId"]+1; _this.drawId = stepData["drawId"] + 1;
} }
}); });
}, },
loadDataInSteps(content,isNewData, callAfterEveryStep, doneCallback) { loadDataInSteps(content, isNewData, callAfterEveryStep, doneCallback) {
var _this = this; var _this = this;
function lData(index) { function lData(index) {
for(var i=index;i<content.length;i++) { for (var i = index; i < content.length; i++) {
if(content[i]["t"]==="addImgBG" && content[i]["draw"]=="1") { if (content[i]["t"] === "addImgBG" && content[i]["draw"] == "1") {
_this.handleEventsAndData(content[i], isNewData, function() { _this.handleEventsAndData(content[i], isNewData, function () {
callAfterEveryStep(content[i], i); callAfterEveryStep(content[i], i);
lData(i+1); lData(i + 1);
}); });
break; break;
} else { } else {
@ -694,31 +695,31 @@ var whiteboard = {
}, },
loadJsonData(content) { loadJsonData(content) {
var _this = this; var _this = this;
_this.loadDataInSteps(content, false, function(stepData, index) { _this.loadDataInSteps(content, false, function (stepData, index) {
_this.sendFunction(stepData); _this.sendFunction(stepData);
if(index>=content.length-1) { //Done with all data if (index >= content.length - 1) { //Done with all data
_this.drawId++; _this.drawId++;
} }
}); });
}, },
sendFunction : function(content) { //Sends every draw to server sendFunction: function (content) { //Sends every draw to server
var _this = this; var _this = this;
content["wid"] = _this.settings.whiteboardId; content["wid"] = _this.settings.whiteboardId;
content["username"] = _this.settings.username; content["username"] = _this.settings.username;
content["drawId"] = _this.drawId; content["drawId"] = _this.drawId;
var tool = content["t"]; var tool = content["t"];
if(_this.settings.sendFunction) { if (_this.settings.sendFunction) {
_this.settings.sendFunction(content); _this.settings.sendFunction(content);
} }
if(tool==="line" || tool==="pen" || tool==="rect" || tool==="circle" || tool==="eraser" || tool==="addImgBG" || tool==="recSelect" || tool==="eraseRec") { if (tool === "line" || tool === "pen" || tool === "rect" || tool === "circle" || tool === "eraser" || tool === "addImgBG" || tool === "recSelect" || tool === "eraseRec") {
_this.drawBuffer.push(content); _this.drawBuffer.push(content);
} }
}, },
isRecRecCollision : function(rx1,ry1,rw1,rh1,rx2,ry2,rw2,rh2) { isRecRecCollision: function (rx1, ry1, rw1, rh1, rx2, ry2, rw2, rh2) {
return rx1 < rx2 + rw2 && rx1 + rw1 > rx2 && ry1 < ry2 + rh2 && rh1 + ry1 > ry2; return rx1 < rx2 + rw2 && rx1 + rw1 > rx2 && ry1 < ry2 + rh2 && rh1 + ry1 > ry2;
}, },
isRecPointCollision : function(rx, ry, rw, rh, px, py) { isRecPointCollision: function (rx, ry, rw, rh, px, py) {
return rx <= px && px <= rx + rw && ry <= py && py <= ry + rh; return rx <= px && px <= rx + rw && ry <= py && py <= ry + rh;
} }
} }