Canvas缩放平移后如何确保点击正确的矩形?
解决方案:正确的坐标逆变换匹配逻辑
问题核心在于你现在是将瓦片坐标转换为屏幕坐标后与鼠标位置比较,但由于Canvas的变换顺序(平移→缩放→平移),这种正向转换容易出错。正确的做法是将鼠标的屏幕坐标逆转换为瓦片所在的世界坐标,再直接和瓦片的原始坐标范围对比。
步骤解析
你的update函数中,Canvas上下文的变换顺序是:
- 平移到画布中心:
translate(window.innerWidth/2, window.innerHeight/2) - 缩放:
scale(this.cameraZoom, this.cameraZoom) - 应用相机偏移:
translate(-window.innerWidth/2 + this.cameraOffset.x, -window.innerHeight/2 + this.cameraOffset.y)
要得到鼠标对应的世界坐标,需要按逆顺序抵消这些变换:
- 先抵消相机偏移的平移
- 再抵消缩放(除以缩放倍数)
- 最后抵消画布中心的平移
修改后的涂色判断函数
setPaintingColor = (game) => { if (!game.mouse.down) { return; } // 将鼠标屏幕坐标转换为世界坐标 const canvasCenterX = window.innerWidth / 2; const canvasCenterY = window.innerHeight / 2; const worldX = (game.mouse.x - canvasCenterX) / game.cameraZoom + canvasCenterX - game.cameraOffset.x; const worldY = (game.mouse.y - canvasCenterY) / game.cameraZoom + canvasCenterY - game.cameraOffset.y; // 计算瓦片在世界空间的范围(原始坐标,无需缩放) const tileMinX = this.x - game.gap; const tileMaxX = this.x + this.width - game.gap; const tileMinY = this.y - game.gap; const tileMaxY = this.y + this.height - game.gap; // 判断鼠标是否在瓦片范围内 if ( worldX >= tileMinX && worldX <= tileMaxX && worldY >= tileMinY && worldY <= tileMaxY ) { this.color = "yellow"; } };
关键说明
- 无需单独处理拖拽位移:
cameraOffset已经包含了拖拽后的最终偏移量,逆变换时直接使用它即可,不用再计算dragStart和dragEnd的差值 - 世界坐标与瓦片原始坐标直接对比:避免了多次变换带来的计算误差,逻辑更清晰
- 修正
update函数的小问题:原代码中ctx.clearRect(0, 0, window.width, window.height)的window.width应为window.innerWidth,否则可能导致清理范围错误
内容的提问来源于stack exchange,提问作者GeraltDieSocke
相关产品推荐
相关产品推荐

