This drawing application worked perfectly on my laptop. Testing on different screen sizes, the line drawn does not align with the cursor. I think that I will have to apply some scaling mechanism.
// DRAWING FUNCTIONALITY
var canvas, ctx, painting = false,
previousMousePos;
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
}
};
// Sender drawing function.
function drawLineImmed(x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.strokeStyle = 'white';
ctx.stroke();
};
// Receiver drawing function.
function drawLineTwo(data) {
ctx.beginPath();
ctx.moveTo(data.px, data.py);
ctx.lineTo(data.mx, data.my);
ctx.strokeStyle = 'white';
ctx.stroke();
};
// Get draw data. Pass to receiver drawing function.
socket.on('draw', function(data) {
drawLineTwo(data);
});
// Sender emit drawing data.
function mouseMove(evt) {
var mousePos = getMousePos(canvas, evt);
if (painting) {
drawLineImmed(previousMousePos.x, previousMousePos.y, mousePos.x, mousePos.y);
socket.emit('draw', {px:previousMousePos.x, py:previousMousePos.y, mx:mousePos.x, my:mousePos.y}, page);
previousMousePos = mousePos;
};
};
function clicked(evt) {
previousMousePos = getMousePos(canvas, evt);
painting = true;
};
function release(evt) {
painting = false;
};
function leave(evt) {
painting = false;
};
$(document).ready(function() {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
painting = false;
canvas.addEventListener('mousemove', mouseMove, false);
canvas.addEventListener('mousedown', clicked);
canvas.addEventListener('mouseup', release);
canvas.addEventListener('mouseleave', leave);
});
// CSS
#canvas {
border-radius: 2px;
background-color: rgb(33,37,43);
position: fixed;
left: 1.7%;
top: 3%;
border-radius: 8px;
border-style: solid;
border-width: 3px;
border-color: black;
width: 80%;
}
What has to scale relative to what?