Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

232
Views
Mouse offset not correct in HTML5 canvas

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

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!