在使用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>
标签:canvas,ctx,画布,拖影,HTML,var,rect,lasting From: https://www.cnblogs.com/shiyixirui/p/18632877