First I simplified the mouse tracking code on the right by:
function mouseDraw(e){
let bound = canvas.getBoundingClientRect();
let x = e.clientX ;
let y = e.clientY ;
// subtract half the width and height to
get shape to draw at center
c.fillRect(x-8, y-8, 16, 16);
};
track mouse position from stack overflow
canvas.addEventListener('click', event => {
let bound = canvas.getBoundingClientRect();
let x = event.clientX - bound.left - canvas.clientLeft;
let y = event.clientY - bound.top - canvas.clientTop;
context.fillRect(x, y, 16, 16);
});
I was able to add the function to the 'mousedown'
listner and
remove it in the 'mouseup
listner
function mouseDraw(e){ let bound = canvas.getBoundingClientRect(); // console.log("clientX",event.clientX,"clientY:",event.clientY) let x = e.clientX ; let y = e.clientY ; c.lineWidth = 2; c.strokeStyle = "black" c.fillStyle = "lightblue" // subtract half the width and height to get shape to draw at center c.fillRect(x-8,y-8,16,16) c.strokeRect(x-8, y-8, 16, 16); }; // Took the the code below from // https://www.youtube.com/watch?v=adPc41k4EvE canvas.addEventListener('mousedown',() => { canvas.addEventListener('mousemove',mouseDraw) }); canvas.addEventListener('mouseup',() => { canvas.removeEventListener('mousemove',mouseDraw) });