Canvas闪烁圆点功能失效,请求技术排查
问题分析与修复
你的代码无法正常运行主要有几个关键问题:
- 全局函数未定义错误:你直接写了
moveTo(xcoor,ycoor);,但这个方法是Canvas上下文对象的专属方法,必须通过ctx.moveTo()调用。而且实际上绘制圆形的arc方法会自动将路径起始点移到圆弧起点,这行代码完全可以删掉。 - HTML结构不规范:
<h1>标签被放在了<body>标签外面,不符合HTML解析规范,得把它移到<body>内部。 - 冗余重复操作:每次定时器触发都重新获取canvas元素、上下文对象,还重复定义
getRandomInt函数,这些操作只需要执行一次,放在定时器外部能避免不必要的性能消耗。 - 注释与变量不匹配:
var x = 1280;//will be equal to window height这类注释写反了,x对应的是画布宽度,y对应的是画布高度。
修复后的完整代码:
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"/> <title>Peripheral vision checker</title> <script type="application/javascript"> // 提取随机数生成函数,避免重复定义 function getRandomInt(max) { return Math.floor(Math.random() * max); } function draw() { const onFor = 1000; // 提前获取canvas和上下文,避免每次定时器触发都重复获取 const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const canvasWidth = 1280; const canvasHeight = 720; setInterval(() => { // 绘制白色矩形清除画布 ctx.fillStyle = 'white'; ctx.fillRect(0, 0, canvasWidth, canvasHeight); // 生成随机坐标 const xcoor = getRandomInt(canvasWidth); const ycoor = getRandomInt(canvasHeight); // 绘制蓝色圆点 ctx.fillStyle = 'blue'; const radius = 10; ctx.beginPath(); // 开启新路径,避免和之前的路径叠加导致填充异常 ctx.arc(xcoor, ycoor, radius, 0, 2 * Math.PI); ctx.fill(); }, onFor); } </script> </head> <body onload="draw();"> <h1>Peripheral vision checker</h1> <canvas id="canvas" width="1280" height="720"></canvas> </body> </html>
额外说明:修复时新增了ctx.beginPath(),目的是每次绘制圆形都开启独立路径,避免多次绘制后路径叠加导致填充效果异常。
内容的提问来源于stack exchange,提问作者ofey
相关产品推荐
相关产品推荐

