簡體   English   中英

clearRect不清除畫布

[英]clearRect does not clear the canvas

我正在嘗試在畫布上繪制矩形,用戶點選並移動鼠標,將繪制該矩形,完成繪制后,只有一個矩形會保留,另一個矩形。 但是使用

 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> 

小提琴

clearRect調用不起作用,因為先前的矩形仍然可見。

沒有理由不起作用,為什么它會有這種表現呢? 清除矩形后,將繪制新圖像,並且所有先前的矩形都應消失。

我看到您在最后調用stroke() ,這可能是問題所在。 在此處查看“使用注意事項”:

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

clearRect的一個常見問題是,當未正確使用路徑時,它可能無法正常工作。 不要忘記在調用clearRect之后開始繪制新框架之前先調用beginPath()。

嘗試:用beginPath()調用后clearRect()

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

添加一個對象以維持狀態。 您的代碼只是堆疊事件偵聽器並創建單個形狀。 我們使用context.beginPath()來建議一種新形狀。

 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM