I am trying to draw rectangle in canvas, users click on spot and moves the mouse, the rectangle will be drawn and when its done only one rectangle remanins, the alst one. However using
let canvas = document.querySelector("canvas"), ctx = canvas.getContext("2d");
canvas.addEventListener("mousedown",function(event){
x_ = event.pageX - this.offsetLeft;
y_ = event.pageY - this.offsetTop;
canvas.addEventListener("mousemove",function(event){
xmax = event.pageX - this.offsetLeft;
ymax = event.pageY - this.offsetTop;
console.log(x_,y_,xmax,ymax);
ctx.clearRect(0,0,canvas.width,canvas.height)
ctx.fillRect(0, 0, 10, 10);
ctx.rect(x_,y_,xmax-x_,ymax-y_);
ctx.stroke()
})
})
canvas {
border: 1px solid black;
}
<canvas></canvas>
The clearRect call does not work, as the previous rectangles remain visible.
There is no reason for it not to work, why does it behaves in such way? After clearing the rectangle, the new image is drawn, and all previous rectangles should go away.
stroke()at the end. Check the "Usage notes" section here: developer.mozilla.org/en-US/docs/Web/API/…