蝴蝶刀刀
您调用setTransform(a, b, c, d, e, f)创建一个 3x3仿射变换矩阵:| a c e || b d f || 0 0 1 |给定您当前的值 (1, 0.5, -1, 0.5, n, 0) 有一个逆矩阵:| 0.5 1 -n/2 | | -0.5 1 +n/2 || 0 0 1 |将该变换矩阵应用于您的鼠标坐标(需要表示为 1x3 矩阵[x, y, 1]应提供所需的网格坐标:const rows = 10;const columns = 6;const $coordinate = $("#coordinate");const $canvas = $("#canvas");canvas.width = (rows * 32) + (columns * 32);canvas.height = (rows * 16) + (columns * 16);const context = $canvas[0].getContext("2d");context.imageSmoothingEnabled = false;context.save(); context.fillStyle = "white";context.setTransform(1, 0.5, -1, 0.5, (columns * 32), 0);// (a) horizontal scaling: 1// (b) horizontal skewing: 0.5// (c) vertical skewing: -1// (d) vertical scaling: 0.5// (e) horizontal moving: (columns * 32)// (f) vertical moving: 0for(let row = 0; row < rows; row++) { for(let column = 0; column < columns; column++) { context.rect(row * 32, column * 32, 31.5, 31.5); }}context.fill();$canvas.mousemove(function(e) { const position = { left: e.pageX - $canvas.offset().left, top: e.pageY - $canvas.offset().top }; const innerPosition = { left: position.left * 0.5 + position.top - (columns * 32) / 2, top: position.left * -0.5 + position.top + (columns * 32) / 2 }; const coordinate = { row: Math.floor(innerPosition.top / 32), column: Math.floor(innerPosition.left / 32) }; $coordinate.html(coordinate.row + "x" + coordinate.column);});#canvas { background: green;}#coordinate { position: absolute; font-family: Arial, sans-serif; font-size: 16px; left: 12px; top: 12px;}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><canvas id="canvas"></canvas><div id="coordinate">0x0</div>