Drawing with canvas continuous line

Viewed 26

I wrote this code to draw free lines like paint,

const canvas = document.getElementById("canv");
let mousedown = false;
const ctx = canvas.getContext("2d");
ctx.lineWidth = 5;
let x;
let y;
window.addEventListener("mousedown", (event) => {

  console.log('clicked');
  if (event.which == 3) {
    mousedown = false;

  } else if (event.which == 1) {
    mousedown = true;
  }

  window.addEventListener('contextmenu', (event) => {
    event.preventDefault();
  })

  window.addEventListener("mousemove", (event) => {
    if (mousedown) {
      document.body.style.cursor = "crosshair";
      console.log("MOVING");
      ctx.beginPath();
      x = event.clientX - 100;
      y = event.clientY - 100;
      ctx.moveTo(x, y);
      ctx.arc(x, y, 2, 0, 2 * Math.PI, false);
      ctx.strokeStyle = 'black';
      ctx.stroke();
      ctx.closePath();
    } else if (!mousedown) {
      document.body.style.cursor = "crosshair";
      console.log("MOVING");
      ctx.beginPath();
      x = event.clientX - 100;
      y = event.clientY - 100;
      ctx.moveTo(x, y);
      ctx.arc(x, y, 0.5, 0, 2 * Math.PI, true);
      ctx.strokeStyle = 'white';
      ctx.stroke();
      ctx.closePath();
    }

  })
})
canvas {
  position: absolute;
  top: 100px;
  left: 100px;
  border: 1px solid;
}
<canvas id="canv" width="700" height="700" ">
        Your Browser Doesn't Support Canvas.
    </canvas>

The code is working, but I can only draw with certain speed, otherwise the line becomes distributed circles, is there any property or function to fix this issue?

1 Answers

Don't use circles, use lines instead. Have memory that keeps track of the previous position and draw the line from there.

const canvas = document.getElementById("canv");
let mousedown = false;
const ctx = canvas.getContext("2d");
ctx.lineWidth = 5;
let x;
let y;
let memx;//memory for previous position
let memy;

window.addEventListener("mousedown", (event) => {
memx = event.clientX-100;//set starting position
memy = event.clientY-100;

ctx.beginPath();
console.log('clicked');
if (event.which == 3) {
mousedown = false;

} else if (event.which == 1) {
 mousedown = true;
}

window.addEventListener('contextmenu', (event) => {
 event.preventDefault();
})

window.addEventListener("mousemove", (event) => {
if (mousedown) {
  document.body.style.cursor = "crosshair";
  console.log("MOVING");

  x = event.clientX - 100;
  y = event.clientY - 100;
  ctx.moveTo(memx, memy);
   ctx.lineTo(x,y);
  memx = x;
  memy = y;
  ctx.strokeStyle = 'black';
  ctx.stroke();
} else if (!mousedown) {
  document.body.style.cursor = "crosshair";
  console.log("MOVING");
  ctx.beginPath();
  x = event.clientX - 100;
  y = event.clientY - 100;
  ctx.moveTo(memx, memy);
  ctx.lineTo(x,y);
  memx = x;
  memy = y;
  ctx.stroke();
 ctx.closePath();
}
})
})
Related