HTML5 Canvas网格系统点击上色位置偏移问题排查求助
问题修复方案
你代码里一共存在2个逻辑错误,修改后即可解决偏移问题:
1. 点击坐标计算逻辑写反
在game-engine.js的点击事件回调中,你把横纵坐标的偏移扣除逻辑搞反了,导致坐标本身计算错误:
原错误代码:
let mouseY = e.clientY - x; let mouseX = e.clientY - y;
修改为:
let mouseX = e.clientX - x; let mouseY = e.clientY - y;
说明:getBoundingClientRect返回的x是画布距离视口左侧的偏移量,对应横坐标计算要扣除它;y是画布距离视口顶部的偏移量,对应纵坐标计算要扣除它。
2. 格子索引计算的除数错误
你渲染网格时每个单元格的实际占位宽度/高度是cellSize + padding,但在drawOnGrid方法中计算点击坐标属于哪个格子时,只除以了纯单元格尺寸cellSize,没有算入padding的宽度,越远的位置padding累积的误差就越大,自然偏移越来越严重。
原错误代码:
let posX = Math.floor(x / this.cellSize) * (this.cellSize + this.padding); let posY = Math.floor(y / this.cellSize) * (this.cellSize + this.padding);
修改为:
const unitSize = this.cellSize + this.padding; let posX = Math.floor(x / unitSize) * unitSize; let posY = Math.floor(y / unitSize) * unitSize;
内容的提问来源于stack exchange,提问作者Kristian Vasilev
相关产品推荐
相关产品推荐

