画布上的画线点缀着

Kar*_*ngh 5 javascript

我试图在彩虹笔画画布上工作,但每当我画画时,线条都会出现点缀.只有当我移动得非常慢时才能正常显示.

'mousemove'事件监听器,实际上无法检测到快速更改,或者我的代码中是否存在其他问题?此外,这里是codepen链接,如果有人想要一个工作程序.

这是codepen!

const canvas = document.querySelector('#draw');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext("2d");
ctx.lineWidth = 50;
ctx.lineCap = "round";
ctx.lineJoin = "line";
ctx.strokeStyle = 0;
let hue = 0;
var [x, y] = [0, 0];
let paint = false;

canvas.addEventListener('mousedown', beginDraw);

function beginDraw(e) {
  paint = true;
  [x, y] = [e.x, e.y];
  // ctx.moveTo(x, y);
}

canvas.addEventListener('mousemove', draw);

function draw(e) {
  if (paint == false)
    return;
  ctx.strokeStyle = `hsla(${hue}, 100%, 50%, 0.5)`;
  ctx.beginPath();
  ctx.moveTo(x, y);
  ctx.lineTo(e.x, e.y);
  ctx.stroke();
  [x, y] = [e.x, e.y];
  hue++;
}

canvas.addEventListener('mouseup', endDraw);

function endDraw() {
  paint = false;
}
Run Code Online (Sandbox Code Playgroud)

Łuk*_*ski 1

我认为问题在于 hsla 颜色函数的不透明度。因为它设置为 0.5,所以您有一定的透明度,并且因为您为每个鼠标移动绘制一条线,所以您为绘图的每个鼠标移动事件的起点和终点绘制了一条线。有时这些点相互重叠。

您可以删除透明度并将其保留为 1。在这种情况下,您将不再看到两个点绘制在另一个点之上的位置,从而使其他人更容易看到颜色。

ctx.strokeStyle = `hsla(${hue}, 100%, 50%, 1)`;
Run Code Online (Sandbox Code Playgroud)

如果您不喜欢在颜色变化时看到点,您将需要使用更多的颜色值来使用其他参数,而不仅仅是色调参数,因为颜色步长可能太大,并且当颜色变化时您可能会看到边缘。