I have made a paint app in HTML5 canvas by which user can paint with mouse. But the issue is that there is a slight mouse pointer offset coming when the user draws something and the drawing is not exactly in the point where mouse is clicked. I am attaching a relevant portion of my code.
var canvas = document.querySelector('#board');
this.ctx = canvas.getContext('2d');
function drawOnCanvas() {
var ctx = this.ctx;
var sketch = document.querySelector('#sketch');
var sketch_style = getComputedStyle(sketch);
// Make it visually fill the positioned parent
canvas.style.width ='100%';
canvas.style.height='80%';
// ...then set the internal size to match
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
var mouse = {x: 0, y: 0};
var last_mouse = {x: 0, y: 0};
//for clearing the board
document.getElementById('clr').addEventListener('click', function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}, false);
/* Mouse Capturing Work */
canvas.addEventListener('mousemove', function(e) {
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
}, false);
/* Drawing on Paint App */
ctx.lineWidth = 5;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = 'blue';
// setTimeout(()=>{
// ctx.strokeStyle = (writeMode===1)?'blue':'white'; //choose pen or eraser (pen is 1 and eraser is 0)
// },100)
canvas.addEventListener('mousedown', function(e) {
canvas.addEventListener('mousemove', onPaint, false);
}, false);
canvas.addEventListener('mouseup', function() {
canvas.removeEventListener('mousemove', onPaint, false);
}, false);
var root = this;
var onPaint = function() {
ctx.beginPath();
ctx.moveTo(last_mouse.x, last_mouse.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.closePath();
ctx.stroke();
if(root.timeout != undefined) clearTimeout(root.timeout);
root.timeout = setTimeout(function(){
var base64ImageData = canvas.toDataURL("image/png");
root.socket.emit("canvas-data", base64ImageData);
}, 1000)
};
}
Someone please give an idea how to correct that