If you move the mouse slowly, there are no gaps, but if you accelerate a little, very large gaps appear. How can I fix it? Or do you need a different approach?

const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); canvas.width = 1024; canvas.height = 678; canvas.onmousedown = function() { let flag = true; draw(); canvas.onmousemove = function() { if (flag == true) { draw(); } } canvas.onmouseup = function() { flag = false; } canvas.onmouseout = function() { flag = false; } }; function draw() { let x = event.offsetX; let y = event.offsetY; ctx.fillStyle = 'black'; ctx.fillRect(x, y, 5, 5); } 
 <style> canvas { border: 1px solid; } </style> <canvas id="canvas"></canvas> 

    1 answer 1

    Naturally, there will be a gap between your squares if you move the mouse more than five pixels.

     const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); canvas.width = 1024; canvas.height = 678; var oldPoint = null; let flag = false; canvas.onmousedown = function(e) { flag = true; draw(e); }; canvas.onmousemove = function(e) { if (flag == true) { draw(e); } }; canvas.onmouseup = function() { oldPoint = null; flag = false; }; canvas.onmouseout = function() { oldPoint = null; flag = false; }; function draw(event) { if (!oldPoint) { oldPoint = { x: event.offsetX, y: event.offsetY }; } ctx.moveTo(oldPoint.x, oldPoint.y); ctx.lineTo(event.offsetX, event.offsetY); ctx.strokeStyle = "#FF0000"; ctx.stroke(); oldPoint.x = event.offsetX; oldPoint.y = event.offsetY; } 
     canvas { border: 1px solid; } 
     <canvas id="canvas"></canvas>