Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save piecedigital/73094baeb81447e1961b83e4a0dbffd8 to your computer and use it in GitHub Desktop.
Save piecedigital/73094baeb81447e1961b83e4a0dbffd8 to your computer and use it in GitHub Desktop.
function mouseGridPosition(e,
{
pixel,
w,
h
}) {
// w and h are the width and height of the canvas
var { canvas, context: ctx } = getCanvasAndContext();
var mX = e.offsetX;
var mY = e.offsetY;
var gridOffsetX = Math.floor( (mX / canvas.width) * pixel);
var gridOffsetY = Math.floor( (mY / canvas.height) * pixel);
var x = (gridOffsetX/pixel) * w;
var y = (gridOffsetY/pixel) * h;
var data = {
left: x,
top: y,
right: x + w/pixel,
bottom: y + h/pixel,
canvasWidth: w,
canvasHeight: h,
pixel,
canvas,
context: ctx,
width: w/pixel,
height: h/pixel,
rawMouseX: mX,
rawMouseY: mY
};
data.centerX = data.left + (data.width / 2);
data.centerY = data.top + (data.height / 2);
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment