Skip to content

Instantly share code, notes, and snippets.

@cheeaun
Created March 21, 2020 12:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cheeaun/85274bbea89c06cbdc3eb42732f6d318 to your computer and use it in GitHub Desktop.
Save cheeaun/85274bbea89c06cbdc3eb42732f6d318 to your computer and use it in GitHub Desktop.
Resize (2D but flat) array of values with nearest neighbour algorithm
const width = 300;
const height = 200;
const newWidth = width * 2;
const newHeight = height * 2;
const xRatio = width / newWidth;
const yRatio = height / newHeight;
const resizeValues = (id, values) => {
const newValues = new Array(newWidth * newHeight);
for (let i = 0; i < newHeight; i++) {
for (let j = 0; j < newWidth; j++) {
const x = ~~(j * xRatio); // ~~ = Math.floor but faster
const y = ~~(i * yRatio);
newValues[i * newWidth + j] = values[y * width + x];
}
}
return newValues;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment