skip to Main Content

im making a simple drawing app but whenever i try to draw something it doesnt appear right instead it just looks like bunch of dots however if i move my mouse slowly, it appears right.

here is my code:

const ctx = canvas.getContext('2d');

let draw = false;

let currentX, currentY;

let lineWidth = 15;

document.addEventListener('mousedown', (e) => {
    draw = true;
})

document.addEventListener('mouseup', (e) => {
    draw = false;
})

document.addEventListener('mousemove', startDrawing)



function startDrawing(e) {
    if(!draw) return

    currentX = e.clientX
    currentY = e.clientY

    ctx.lineWidth = lineWidth;
    ctx.lineCap = "round";
    ctx.beginPath();
    ctx.moveTo(currentX, currentY);
    ctx.lineTo(currentX, currentY);
    ctx.stroke()
}```  
.

2

Answers


  1. The Problem is, you draw each time the mousemove event is triggered. The event is not triggered for each pixel you move.

    You need to store the position of the last event and then connect the positions with lines.

    Login or Signup to reply.
  2. The problem is on every line’s starting point. If you move up to P then draw a line up to P, the result is clearly a dot.

    Instead, leverage the cached coordinate pair for the initial move, then draw the line up to where the cursor is. Finally, update the cache.

    function startDrawing(e) {
        if(!draw) return
    
        //currentX = e.clientX
        //currentY = e.clientY
    
        ctx.lineWidth = lineWidth;
        ctx.lineCap = "round";
        ctx.beginPath();
        ctx.moveTo(currentX, currentY);
        ctx.lineTo(e.clientX, e.clientY);
        //ctx.lineTo(currentX, currentY);
        ctx.stroke()
    
        currentX = e.clientX
        currentY = e.clientY
    }
    

    To make the things better, you should avoid to draw the first line from when the mouse is pressed. Try to draw something, then release, then draw again: you’ll see that there’s a line connecting the last point of the first session with the first of the last one.

    To correct this, you can adjust as follows:

    document.addEventListener('mousedown', (e) => {
        draw = true;
        currentX = currentY = undefined;
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search