I'm trying to reappear a 'select-function' of windows mspaint or other drawing tools on canvas, which works like:
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);