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

213
Views
how 'mousemove' event work on html5 canvas?

I'm trying to reappear a 'select-function' of windows mspaint or other drawing tools on canvas, which works like:

  1. when mouse is down, mark this point
  2. when mouse is moving, draw a rect from mousedown point to now mouse position
  3. when mouse is up, preserve the rect on canvas and end select

I'm now confused of how 'mousemove' event working when mouse moves? When mouse is moving, it draws lots of rects on the canvas.

code as:

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

function windowToCanvas(x,y) {
    let rect = canvas.getBoundingClientRect();
    x = x - rect.left * (canvas.width / rect.width);
    y = y - rect.top * (canvas.height / rect.height);
    return [x,y];
}
let mRect = {x:0,y:0,w:0,h:0};
function handleMouseMove(e){
    let temp = windowToCanvas(e.clientX,e.clientY);
    [mRect.w,mRect.h] = [temp[0]-mRect.x,temp[1]-mRect.y];
    ctx.clearRect(0,0,canvas.width,canvas.height);  // this line seems not working
    ctx.rect(mRect.x,mRect.y,mRect.w,mRect.h);
    ctx.stroke();
    
}
function handleMouseDown(e){
    [mRect.x,mRect.y]=windowToCanvas(e.clientX,e.clientY)
    canvas.addEventListener('mousemove',handleMouseMove);
    canvas.addEventListener('mouseup',()=>{
        console.log('mouseup')
        canvas.removeEventListener('mousemove',handleMouseMove)
    },{once:true});
}
canvas.addEventListener('mousedown',handleMouseDown);
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!