How to draw on HTML5 canvas using a mouse with JavaScript?

Spread the love

Sometimes, we want to draw on HTML5 canvas using a mouse with JavaScript.

In this article, we’ll look at how to draw on HTML5 canvas using a mouse with JavaScript.

How to draw on HTML5 canvas using a mouse with JavaScript?

To draw on HTML5 canvas using a mouse with JavaScript, we add mouse event listeners.

For instance, we write

const canvas = document.createElement("canvas");
document.body.appendChild(canvas);

document.body.style.margin = 0;
canvas.style.position = "fixed";

const ctx = canvas.getContext("2d");
resize();

const pos = { x: 0, y: 0 };

const setPosition = (e) => {
  pos.x = e.clientX;
  pos.y = e.clientY;
};

const resize = () => {
  ctx.canvas.width = window.innerWidth;
  ctx.canvas.height = window.innerHeight;
};

const draw = (e) => {
  if (e.buttons !== 1) {
    return;
  }

  ctx.beginPath();

  ctx.lineWidth = 5;
  ctx.lineCap = "round";
  ctx.strokeStyle = "#c0392b";

  ctx.moveTo(pos.x, pos.y);
  setPosition(e);
  ctx.lineTo(pos.x, pos.y);

  ctx.stroke();
};

window.addEventListener("resize", resize);
document.addEventListener("mousemove", draw);
document.addEventListener("mousedown", setPosition);
document.addEventListener("mouseenter", setPosition);

to call addEventListener to listen to the mousemove, mousedown, and mouseenter events.

In the draw function, we call moveTo and the lineTo with the mouse’s x and y coordinates to draw a line that goes through the point.

We call stroke to render the line.

The setPosition function gets the current mouse position.

Conclusion

To draw on HTML5 canvas using a mouse with JavaScript, we add mouse event listeners.

Leave a Reply

Your email address will not be published.