1

How can I make a JS Script that lets my user create points on an HTML canvas?

I want them to click somewhere and a point (circle) to appear there. I also need this point to be used when creating a line using

ctx.beginPath();
ctx.moveTo(POINT_A);
ctx.lineTo(POINT_B);
ctx.stroke();
Michael M.
  • 10,486
  • 9
  • 18
  • 34
maruan
  • 57
  • 9

1 Answers1

1

Here's a simple example which draws a line between every point created.

  • First add a click event listener to your canvas.
  • Using click event, deduce coordinates of point clicked.
  • Draw a point on canvas. Currently the point is a rectangle. If you want other shapes, check out this post.
  • Draw a line from previous point to current point.

const canvas = document.getElementById("myCanvas");
let pointA = null;
let pointB = null;
let clicks = 0; //number of clicks

function displayPoint(x, y) {
  //display point at  (x,y)
  let ctx = canvas.getContext("2d");
  ctx.fillRect(x, y, 1, 1);
}

function drawLine(pointA, pointB) {
  if (pointA == null || pointB == null) return;
  let ctx = canvas.getContext("2d");
  ctx.beginPath();
  ctx.moveTo(pointA[0], pointA[1]);
  ctx.lineTo(pointB[0], pointB[1]);
  ctx.stroke();
}

canvas.addEventListener("click", (e) => {
  clicks++;
  const rect = canvas.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;

  displayPoint(x, y);

  if (clicks % 2 === 1) {
    pointA = [x, y];
  } else {
    pointB = [x, y];
  }
  drawLine(pointA, pointB);
});
body {
  height: 100vh;
  width: 100vw;
  display: grid;
  place-content: center;
}
<canvas id="myCanvas" width="200" height="100" style="border: 1px solid #000000">
    </canvas>
Bunny
  • 1,180
  • 8
  • 22
  • It worked, thank you!! Just three questions How do I change the color of the points and lines? How can I get the length of the line (so I can then display it to the user)? How can I clean the line? Like add a button or shortcut to delete it and re-start the drawing)? Thank you again! =) – maruan Nov 01 '22 at 06:51
  • Use `ctx.strokeStyle` to change line color. To get length of a line, simply use [pythagoras theorem](https://byjus.com/maths/distance-between-two-points-formula/). View [this asnwer](https://stackoverflow.com/questions/2142535/how-to-clear-the-canvas-for-redrawing) to clean everything in canvas. If you want to undo only the most recent change, check this [answer](https://stackoverflow.com/questions/53960651/how-to-make-an-undo-function-in-canvas) – Bunny Nov 01 '22 at 12:41