6

Если вести мышь медленно, то промежутков нет, но стоит немного ускорить, появляются очень большие пробелы. Как можно исправить? Или нужен вообще другой подход?

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 1024;
canvas.height = 678;


canvas.onmousedown = function() {
  let flag = true;
  draw();
  canvas.onmousemove = function() {
    if (flag == true) {
      draw();
    }
  }
  canvas.onmouseup = function() {
    flag = false;
  }
  canvas.onmouseout = function() {
    flag = false;
  }
};

function draw() {
  let x = event.offsetX;
  let y = event.offsetY;
  ctx.fillStyle = 'black';
  ctx.fillRect(x, y, 5, 5);

}
<style>
  canvas {
    border: 1px solid;
  }
</style>

<canvas id="canvas"></canvas>

1 ответ 1

4

Естественно, будет просвет между Вашими квадратиками, если Вы двинули мышь больше, чем на пять пикселей.

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 1024;
canvas.height = 678;
var oldPoint = null;
let flag = false;

canvas.onmousedown = function(e) {
  flag = true;
  draw(e);
};
canvas.onmousemove = function(e) {
  if (flag == true) {
    draw(e);
  }
};
canvas.onmouseup = function() {
  oldPoint = null;
  flag = false;
};
canvas.onmouseout = function() {
  oldPoint = null;
  flag = false;
};

function draw(event) {
  if (!oldPoint) {
    oldPoint = { x: event.offsetX, y: event.offsetY };
  }

  ctx.moveTo(oldPoint.x, oldPoint.y);
  ctx.lineTo(event.offsetX, event.offsetY);
  ctx.strokeStyle = "#FF0000";
  ctx.stroke();

  oldPoint.x = event.offsetX;
  oldPoint.y = event.offsetY;
}
canvas {
  border: 1px solid;
}
<canvas id="canvas"></canvas>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.