Skip to content

Instantly share code, notes, and snippets.

@miketahani
Created April 5, 2020 00:48
Show Gist options
  • Save miketahani/a24b678dd44120a9f25cb014106fac87 to your computer and use it in GitHub Desktop.
Save miketahani/a24b678dd44120a9f25cb014106fac87 to your computer and use it in GitHub Desktop.
// for use with pixel buffers, like the one you get from CanvasRenderingContext2D.getImageData(...).data
const getIndexFromCoordinates = (x, y, imageWidth) => y * (imageWidth * 4) + x * 4
const getCoordinatesFromindex = (index, imageWidth) => [
(index / 4) % imageWidth,
Math.floor((index / 4) / imageWidth)
];
// for use with normal arrays where one element represents a cell in a ROWSxCOLS grid
const getIndexFromCoordinates = (x, y, width) => x + y * width;
const getCoordinatesFromIndex = (index, width) => [index % width, Math.floor(index / width)];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment