HTML/JavaScript 中的 beginPath 和 ctx.arc

beginPath and ctx.arc in HTML/JavaScript

我正在尝试制作画板。我正在使用 ctx.beginPath() 并平滑我添加的 ctx.arc()ctx.fill() 的边缘。但问题是,如果我移动鼠标太快,它就不会绘制连续线。它绘制圆圈,圆圈之间有空格。鼠标的速度越快,圆圈之间的空间就越大。这是我的 JS 代码:

var lastX;
var lastY;
var mouseX;
var mouseY;

function handleMouseMove(e) {
    mouseX = parseInt(e.clientX - offsetX);
    mouseY = parseInt(e.clientY - offsetY);

    if (isMouseDown) {
        ctx.beginPath();
        ctx.strokeStyle = x;
        ctx.lineWidth = y;
        if (mode == "pen") { //This is drawing mode (The problem is here)
            ctx.globalCompositeOperation = "source-over";
            ctx.arc(lastX, lastY, y, 0, Math.PI * 2, false);  //y is just strokes width
            ctx.fill();
            ctx.stroke();
        } else {  //This is eraser
            ctx.globalCompositeOperation = "destination-out";
            ctx.arc(lastX, lastY, 8, 0, Math.PI * 2, false);
            ctx.stroke();
            ctx.fill();
        }
        lastX = mouseX;
        lastY = mouseY;
    }
}

画一条路

与其绘制圆弧,不如绘制具有线宽的路径

ctx.lineWidth设置为圆的半径* 2。对于端点设置ctx.lineCap = "round",对于角设置ctx.lineJoin = "round"

基本示例

单击拖动 canvas 进行绘制。

const points = [];
const mouse  = {x : 0, y : 0, button : false}
const ctx = canvas.getContext("2d");
canvas.addEventListener("mousemove", mouseEvents);
canvas.addEventListener("mousedown", mouseEvents);
canvas.addEventListener("mouseup", mouseEvents);
function mouseEvents(e){
    mouse.x = e.pageX - 1;
    mouse.y = e.pageY - 1;
    const lb = mouse.button;
    mouse.button = e.type === "mousedown" ? true : e.type === "mouseup" ? false : mouse.button;
  if (mouse.button) {
      if (!lb) { points.length = 0 }
      points.push({x: mouse.x, y: mouse.y});
      drawPoints();
  } 
}
function drawPoints() {
   ctx.clearRect(0,0, canvas.width, canvas.height);
   ctx.lineWidth = 20;
   ctx.lineCap = "round";
   ctx.lineJoin = "round";
   ctx.beginPath();
   for (const p of points) { ctx.lineTo(p.x, p.y); }
   ctx.stroke();
}
canvas { 
   position : absolute; top : 0px; left : 0px;
   cursor: crosshair;
   border: 1px solid black;
}
<canvas id="canvas" width="256" height="256"></canvas>