Canvas四角绘制正方形异常排查:右下角图形未完成及坐标系疑问
问题分析与修复方案
核心问题
你遇到的右下角正方形绘制不完整,根源有两个:
- Canvas尺寸与计算坐标不匹配:HTML里给Canvas设置了固定宽高
1846x768,但代码里用window.innerWidth/innerHeight(浏览器视口尺寸)计算坐标,还额外给y加了100,导致右下角坐标超出Canvas可见范围。 - 右下角正方形路径未闭合:代码里只画了右下角正方形的两条边,缺少收尾的线条,自然只显示部分图形。
修复步骤
1. 统一Canvas尺寸与坐标计算
用Canvas自身的尺寸来计算绘制坐标,或者让Canvas匹配视口尺寸:
// 替换原x、y的赋值逻辑 const x = canvas.width; const y = canvas.height; // 删掉y = y + 100; 这行代码会让绘制坐标超出Canvas范围
2. 补全右下角正方形的闭合路径
给右下角正方形添加缺失的两条边:
//bottom right ctx.moveTo(x-t,y-t); ctx.lineTo(x,y-t); ctx.lineTo(x,y); ctx.lineTo(x-t,y); // 新增:从右下角向左画到正方形左边缘 ctx.lineTo(x-t,y-t); // 新增:闭合路径回到起点
3. 清理冗余代码
- 删掉重复定义的
getRandomInt函数 - 修正
i++的位置(原代码放在myTimer函数外,完全不会生效) - 避免重复定义变量
t,用更清晰的变量名(比如squareSize)区分不同用途的变量
完整修复后的代码
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <script type="application/javascript"> function getRandomInt(max) { return Math.floor(Math.random() * max); } function draw() { const intervalTime = getRandomInt(10); const canvas = document.getElementById('canvas'); // 让Canvas匹配视口尺寸 canvas.width = window.innerWidth; canvas.height = window.innerHeight; if (canvas.getContext) { const ctx = canvas.getContext('2d'); setInterval(myTimer, intervalTime * 100); function myTimer() { const canvasWidth = canvas.width; const canvasHeight = canvas.height; const squareSize = 10; ctx.beginPath(); const crosshairLength = 20; // 绘制十字线 ctx.moveTo((canvasWidth/2)-crosshairLength, canvasHeight/2); ctx.lineTo((canvasWidth/2)+crosshairLength, canvasHeight/2); ctx.moveTo(canvasWidth/2, (canvasHeight/2)-crosshairLength); ctx.lineTo(canvasWidth/2, (canvasHeight/2)+crosshairLength); // 左上角正方形 ctx.moveTo(0,0); ctx.lineTo(squareSize,0); ctx.lineTo(squareSize,squareSize); ctx.lineTo(0,squareSize); ctx.lineTo(0,0); // 右上角正方形 ctx.moveTo(canvasWidth-squareSize,0); ctx.lineTo(canvasWidth,0); ctx.lineTo(canvasWidth,squareSize); ctx.lineTo(canvasWidth-squareSize,squareSize); ctx.lineTo(canvasWidth-squareSize,0); // 右下角正方形 ctx.moveTo(canvasWidth-squareSize,canvasHeight-squareSize); ctx.lineTo(canvasWidth,canvasHeight-squareSize); ctx.lineTo(canvasWidth,canvasHeight); ctx.lineTo(canvasWidth-squareSize,canvasHeight); ctx.lineTo(canvasWidth-squareSize,canvasHeight-squareSize); // 左下角正方形(原代码未实现,补充完整) ctx.moveTo(0,canvasHeight-squareSize); ctx.lineTo(squareSize,canvasHeight-squareSize); ctx.lineTo(squareSize,canvasHeight); ctx.lineTo(0,canvasHeight); ctx.lineTo(0,canvasHeight-squareSize); ctx.stroke(); } } } </script> </head> <body onload="draw();"> <canvas id="canvas"></canvas> </body> </html>
额外说明
Canvas的坐标系确实是左上角为原点,Y轴正方向向下,你的理解是正确的,问题核心不在坐标系本身,而是尺寸不匹配和路径未闭合。
内容的提问来源于stack exchange,提问作者ofey
相关产品推荐
相关产品推荐

