K
K
kunjut192020-06-29 20:08:51
JavaScript
kunjut19, 2020-06-29 20:08:51

How to draw rectangles on canvas like in Paint?

You need to draw a rectangle on the canvas, as is done in Paint. Namely: poke at a certain point on the canvas and drag the diagonal. Here is what I have at the moment

canvas.addEventListener("mousedown", (e) => {
  last_mousex = e.clientX - canvasx;
  last_mousey = e.clientY - canvasy;
  mousedown = true;
});

canvas.addEventListener("mouseup", (e) => {
  mousedown = false;
});

canvas.addEventListener("mousemove", (e) => {
  mousex = e.clientX - canvasx;
  mousey = e.clientY - canvasy;
  if (mousedown) {
    ctx.clearRect(0, 0, canvas.width, canvas.height); //clear canvas
    ctx.beginPath();
    var width = mousex - last_mousex;
    var height = mousey - last_mousey;
    ctx.rect(last_mousex, last_mousey, width, height);
    ctx.strokeStyle = "black";
    ctx.lineWidth = 10;
    ctx.stroke();
  }
});

This code erases the entire canvas and redraws the rectangle on mouse movement. But I need everything that was before the start of drawing the rectangle to be preserved. Is it possible to implement this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2020-06-29
@kunjut19

S
Sergey, 2020-06-29
@KingstonKMS

Apparently, this is not your code. Otherwise, you would not have asked, because there is even a comment in the code: clear canvas

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question