简体   繁体   中英

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.

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.

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);
    [...]

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM