Darlyn
Darlyn

Reputation: 4938

clearRect does not clear the canvas

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>

Fiddle

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.

Upvotes: 0

Views: 1079

Answers (3)

zfrisch
zfrisch

Reputation: 8660

Add an object to maintain state. Your code is just stacking event listeners and creating a singular shape. We use context.beginPath() to advise of a new shape.

let canvas = document.querySelector("canvas"), ctx = canvas.getContext("2d"),
mouse = { 
mousedown: false,
x: 0,
y: 0
}
canvas.addEventListener("mousedown",function(event){
    mouse.x = event.pageX - this.offsetLeft;
    mouse.y = event.pageY - this.offsetTop;  
    mouse.mousedown = true;
})
canvas.addEventListener("mouseup mouseleave",function(event){

    mouse.mousedown = false;
})
    canvas.addEventListener("mousemove",function(event){
        xmax = event.pageX - this.offsetLeft;
        ymax = event.pageY - this.offsetTop;

        ctx.clearRect(0,0,canvas.width,canvas.height)
        
        if(mouse.mousedown) {
        ctx.fillRect(0, 0, 10, 10);
        ctx.beginPath();
        ctx.rect(mouse.x, mouse.y, xmax-mouse.x,ymax-mouse.y);
        ctx.stroke()
        }
    })
canvas {
border: 1px solid black;
}
<canvas></canvas>

Upvotes: 1

fehrmann
fehrmann

Reputation: 79

Try: Using beginPath() after calling clearRect().

    [...]
    console.log(x_,y_,xmax,ymax);
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.beginPath();
    ctx.fillRect(0, 0, 10, 10);
    [...]

Upvotes: 2

M&#225;t&#233; Safranka
M&#225;t&#233; Safranka

Reputation: 4106

I see you're calling stroke() at the end, that might be the problem. Check the "Usage Notes" here:

https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/clearRect

A common problem with clearRect is that it may appear it does not work when not using paths properly. Don't forget to call beginPath() before starting to draw the new frame after calling clearRect.

Upvotes: 3

Related Questions