document.getElementById("linecap").addEventListener('change', function(){ //add event listener for the select field with the id "linecap". if it changes the value it it will trigger this function
brush = this.value; //save value in variable brush
document.getElementById("color").addEventListener('change', function(){ //add event listener for the input field with the id "linecap". if it changes the value it it will trigger this function
color = this.value; //save value in variable color
document.getElementById("width").addEventListener('change', function(){ //add event listener for the input field with the id "linecap". if it changes the value it it will trigger this function
lineWidth = this.value; //save value in variable lineWidht
});
var canvas = document.getElementById("drawing");
var ctx = canvas.getContext('2d');
var pos = {x: 0, y: 0};
var canvas = document.getElementById("drawing"); //get the canvas element of the html document
var ctx = canvas.getContext('2d'); //get its pixel field in ctx variable
document.addEventListener('mousemove', draw); //add event listener for mouse movement. if it the mouse moves it will trigger function "draw"
document.addEventListener('mousedown', setPosition); //add event listener for mouse buttons if the are pressed down. if it a mouse button is pressed it will trigger function "setPosition"
function setPosition(e){
pos.x = e.clientX - canvas.offsetLeft;
pos.y = e.clientY - canvas.offsetTop;
pos.x = e.clientX - canvas.offsetLeft; //e.clientX is the current mouse X position. canvas.offsetLeft is the canvas position form Left side. this calculation is necessary to really draw in mouse position
pos.y = e.clientY - canvas.offsetTop; //e.clientY is the current mouse Y position. canvas.offsetTop is the canvas position from the Top
}
function draw(e){
if(e.buttons !== 1) return;
ctx.lineWidth = lineWidth;
ctx.lineCap = brush;
ctx.strokeStyle = color;
ctx.beginPath();
ctx.moveTo(pos.x,pos.y);
var startPos = {x: pos.x, y: pos.y};
setPosition(e);
ctx.lineTo(pos.x,pos.y);
ctx.stroke();
socket.emit("picture", {
if(e.buttons !== 1) return; //check if left mouse button is pressed otherwise stop function ("return")
ctx.lineWidth = lineWidth; //change the lineWidth
ctx.lineCap = brush; //change the lineCap
ctx.strokeStyle = color; //change the strokeStyle(color)
ctx.beginPath(); //begin the line
ctx.moveTo(pos.x,pos.y); // start point of the line
var startPos = {x: pos.x, y: pos.y}; //save the start point in variable startPos
setPosition(e); //get the new mouse position (it will be saved in pos.x and pos.y --> see function setPosition
ctx.lineTo(pos.x,pos.y); //draw line to new mouse position
ctx.stroke(); //this is the moment where the actual line is drawn
socket.emit("picture", { //send data to the server
startPos,
pos,
color,
@ -72,7 +72,7 @@ function draw(e){
});
}
socket.on("dingdong", (line) => {
socket.on("dingdong", (line) => { //browser received data from the server(other browser has drawn a line