画布绘制线同时创建1个弯曲的和1个非弯曲的

时间:2019-06-19 05:44:28

标签: javascript canvas

我正在尝试使其仅为1条曲线,但由于某种原因,它是在不需要的锯齿状曲线之后创建它。

我尝试添加和删除,由于某种原因,当删除“ beginPath()”时,线条仍然画出。但是使用bezierCurveTo时,它仍然呈锯齿状,但是当我再次添加“ beginPath()”时再次形成一条平滑线。

const canvas = document.querySelector('#draw');
const ctx = canvas.getContext('2d');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

ctx.strokeStyle = 'hue(100%, 75%, 50%)';
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.lineWidth = 5;
ctx.globalCompositeOperation = 'multiply';

let isDrawing = false;
let lastX = 0;
let lastY = 0;

let points = [];


function draw(e) {
  if (!isDrawing) return;

  var px2 = points.map(point => point.x)[2];
  var py2 = points.map(point => point.y)[2];
  var px1 = points.map(point => point.x)[1];
  var py1 = points.map(point => point.y)[1];
  var px0 = points.map(point => point.x)[0];
  var py0 = points.map(point => point.y)[0];

  ctx.stroke();
  ctx.beginPath();
  ctx.moveTo(px2, py2);

  if (points.length > 3) {
    ctx.bezierCurveTo(px1, py1, px0, py0, e.offsetX, e.offsetY);
  }

  var slope = ((lastY - e.offsetY) + 1) / (Math.abs(lastX - e.offsetX) + 1);

  if (slope < -0.5) {
    if (ctx.lineWidth < 15) {
      ctx.lineWidth++;
    }
  } else {
    if (ctx.lineWidth > 3) {
      ctx.lineWidth -= 1;
    }
  }

  [lastX, lastY] = [e.offsetX, e.offsetY];

  points.unshift({
    x: lastX,
    y: lastY,
    size: ctx.lineWidth,
    color: ctx.strokeStyle,
    mode: "draw"
  });
}

canvas.addEventListener('mousedown', (e) => {
  isDrawing = true;
  [lastX, lastY] = [e.offsetX, e.offsetY];
  ctx.lineWidth = 5;
  points = [];
});

canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('mouseout', () => isDrawing = false);
<canvas id="draw"></canvas>

我希望最终结果只有1条曲线,并除去顶部的锯齿状的一层。

当您真正快速绘制曲线时,您也只能看到两个图层。

感谢您的帮助。

0 个答案:

没有答案