HTML畫布canvas繪制圖形,解決拖影問題
在使用HTMl畫面 canvas 繪制矩形,圓等圖形時,總是出現拖影。
解決這個問題有很多中方法:
方法一:鼠標移動過程中中不畫上去,在釋放鼠標的時候繪制上去,這樣就看不到拖影,但是看不到繪制過程
方法二:在鼠標移動的時候,清除上一次繪制的矩形,然后在畫,這樣就沒有拖影了,但是計算起來麻煩,要多幾行代碼
方法三:結合方法一和方法二,做兩層畫布,重疊顯示,上層作為臨時畫布,下層持久顯示,上層在鼠標移動過程中,清空整個畫布,不用計算上一次的矩形位置
示例代碼(方法三)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <!-- 批注畫布 --> <canvas id="canvas" style="background-color: transparent;border: 1px solid red;position: absolute;top: 100px;left: 100px; z-index: 100;" width="800px" height="600px"></canvas> <canvas id="canvas_lasting" style="background-color: transparent;border: 1px solid red;position: absolute;top: 100px;left: 100px;" width="800px" height="600px"></canvas> <script> var canvas = document.getElementById("canvas"); // 批注畫布-臨時 var ctx = canvas.getContext("2d"); var canvas_lasting = document.getElementById("canvas_lasting"); // 批注畫布 var ctx_lasting = canvas_lasting.getContext("2d"); var state = {"press": false} var rect = {"x":0, "y":0, "w":0, "h":0} canvas.addEventListener("mousedown", (e)=>{ state.press = true; rect = {"x": e.offsetX, "y": e.offsetY, "w": 0, "h": 0} }) canvas.addEventListener("mousemove", (e)=>{ if(state.press){ rect.w = e.offsetX - rect.x; rect.h= e.offsetY - rect.y; ctx.clearRect(0, 0, canvas.width, canvas.height) ctx.beginPath(); ctx.rect(rect.x, rect.y, rect.w, rect.h); ctx.stroke(); } }) canvas.addEventListener("mouseup", (e)=>{ state.press = false; ctx_lasting.beginPath(); ctx_lasting.rect(rect.x, rect.y, rect.w, rect.h); ctx_lasting.stroke(); }) </script> </body> </html>



浙公網安備 33010602011771號