Search code examples
javascripthtmlcanvaspathsmoothing

Draw smoother paths in html canvas


I have a fiddle Here.

When user presses the mouse (mousedown) and then moves the mouse without releasing the mouse I draw the path followed by the mouse. But whe the mouse is moved very fast the drawn path is not smoother anymore.

// this part is drawing the path

            ctx1.save();
            ctx1.beginPath();
            ctx1.moveTo(loc.x, loc.y);
            ctx1.lineTo(loc.x + dX, loc.y + dY);
            ctx1.stroke();

Is there any way to get smoother path on mouse move?

Please ignore the bad programming style for now.

Any help will be great. Thank you


Solution

  • I changed your d.onmousemove to look like this:

    d.onmousemove = function(event) {
        var loc = getMousePos(c, event);
        // nothing is using dX and dY, removed
        if (drawState) {
            if (drawProps.tool === "pencil") {
                ctx1.save();
                ctx1.beginPath();
                ctx1.moveTo(lastX, lastY);// was loc.x and loc.y
                ctx1.lineTo(loc.x, loc.y);// was loc.x + dX and loc.y + dY
                ctx1.stroke();
            } else if (drawProps.tool === "line") {
                ctx.clearRect(0, 0, c.width, c.height);
                ctx.beginPath();
                ctx.moveTo(startX, startY);
                ctx.lineTo(loc.x, loc.y);
                ctx.stroke();
                ctx.closePath();
                ctx.save();
            }
        }
        // Moved to after the if instead of before it
        lastX = loc.x;
        lastY = loc.y;
    };