Pixel rotation
Turns a small sprite to any angle in three ways and counts what each way did to its pixels. One way keeps every pixel, one gives the cleanest outline, and one is what most game engines do, so you can choose with numbers and with your eyes.

When you need it
For anything in your game that turns: a bee, an arrow, a wheel, a sword swing, a car seen from above. Make the frames once from the original sprite, look at all three ways side by side, and keep the one that suits this sprite. The way that keeps every pixel is the only one that never loses a detail of one pixel, such as an eye, and the smooth way gives the shortest outline.
Say this to your AI
Use the pixel rotation recipe from Spielerando. Turn my sprite into 8 frames in each of its three ways, show me the three rows side by side scaled up, and under each frame show me what the count of lost pixels says. I will pick the row.
The code, from https://spielerando.com/en/recipes/pixel-rotation (TypeScript, tested):
```ts
/* Pixel rotation: turns a small sprite to any angle in three ways, and counts what each way did to
its pixels. No way of turning pixel art by a slanted angle is perfect, so the honest answer is
to make all three, look at them and read the counts.
Usage:
const turned = rotate(sprite, 30); // 30 degrees clockwise, every pixel kept
const smooth = rotate(sprite, 30, "smooth"); // cleaner outlines, small details may go
const usual = rotate(sprite, 30, "nearest"); // what most game engines do
lostPixels(sprite, usual); // { "#1f2142": -3 }: three dark pixels fewer
lostPixels(sprite, turned); // {}: nothing lost, nothing doubled
outlineLength(smooth); // a rougher edge is a longer one
const frames = turnFrames(sprite, 8); // a full turn in 8 pictures, all one size
const left = mirror(sprite); // facing the other way
const up = quarterTurns(sprite, -1); // a quarter turn against the clock, exact
`sprite` is { width, height, data } with four numbers a pixel (red, green, blue, opacity), the
shape a canvas uses.
The three ways:
"keep" A turn done as three slides: every row slides sideways by whole pixels, then
every column up or down, then every row again. A slide by whole pixels cannot
lose or double a pixel, so an eye of one pixel never vanishes. The price: each
pixel may land about one pixel off the perfect place, so edges get rougher,
most of all near 45 degrees.
"smooth" The sprite is first drawn nine times as big with its stairs smoothed, and the
turned picture is read from that. Outlines come out cleanest. The price: parts
that are one pixel thin can go missing or change size.
"nearest" Each new pixel takes the old pixel nearest to where it came from. Some old
pixels are then taken twice and some never. It is here to compare against.
Quarter turns and mirroring are exact in every way, and are done first, so only the last 45
degrees or less are ever slanted.
Always turn the original sprite, never one that was turned before, or the damage adds up. The
turned picture sits on a square that is big enough for every angle, and the sprite turns
around the square's middle. To turn around another point, a sword around its handle, say, put
the sprite on a bigger see-through picture first so that this point is the middle.
SPDX-License-Identifier: MIT
Copyright (c) 2026 Spielerando, https://spielerando.com */
export const DEFAULTS = {
/** How many pictures a full turn is cut into: 8 gives one every 45 degrees. */
frames: 8,
/** How a slanted turn is done: "keep" every pixel, "smooth" outlines, or "nearest", the usual way. */
way: "keep",
};
export type Way = "keep" | "smooth" | "nearest";
/** A picture as a canvas holds it: four numbers a pixel (red, green, blue, opacity), row by row. */
export interface Pixels {
width: number;
height: number;
data: Uint8ClampedArray;
}
const blank = (width: number, height: number): Pixels => ({ width, height, data: new Uint8ClampedArray(width * height * 4) });
function copyPixel(from: Pixels, fx: number, fy: number, to: Pixels, tx: number, ty: number): void {
const a = (fy * from.width + fx) * 4;
const b = (ty * to.width + tx) * 4;
to.data[b] = from.data[a];
to.data[b + 1] = from.data[a + 1];
to.data[b + 2] = from.data[a + 2];
to.data[b + 3] = from.data[a + 3];
}
/** The picture facing the other way, or stood on its head. */
export function mirror(pixels: Pixels, direction: "sideways" | "upside-down" = "sideways"): Pixels {
const out = blank(pixels.width, pixels.height);
for (let y = 0; y < pixels.height; y++) {
for (let x = 0; x < pixels.width; x++) {
if (direction === "sideways") copyPixel(pixels, x, y, out, pixels.width - 1 - x, y);
else copyPixel(pixels, x, y, out, x, pixels.height - 1 - y);
}
}
return out;
}
/** The picture turned by quarter turns, clockwise for positive numbers. Exact: no pixel changes, only its place. */
export function quarterTurns(pixels: Pixels, turns: number): Pixels {
if (!Number.isInteger(turns)) throw new Error(`Quarter turns come in whole numbers, not ${turns}. For any other angle use rotate.`);
const n = ((turns % 4) + 4) % 4;
const out = n % 2 === 1 ? blank(pixels.height, pixels.width) : blank(pixels.width, pixels.height);
for (let y = 0; y < pixels.height; y++) {
for (let x = 0; x < pixels.width; x++) {
if (n === 0) copyPixel(pixels, x, y, out, x, y);
else if (n === 1) copyPixel(pixels, x, y, out, pixels.height - 1 - y, x);
else if (n === 2) copyPixel(pixels, x, y, out, pixels.width - 1 - x, pixels.height - 1 - y);
else copyPixel(pixels, x, y, out, y, pixels.width - 1 - x);
}
}
return out;
}
/** The side of the square a sprite of this size is turned on: room for every angle. */
export function roomFor(width: number, height: number): number {
let side = 2 * Math.ceil(Math.hypot(width, height) / 2 + 2);
// the sprite sits exactly in the middle from left to right
if ((side - width) % 2 !== 0) side++;
return side;
}
/** The sprite in the middle of a see-through square with room to turn. */
function withRoom(pixels: Pixels): Pixels {
const side = roomFor(pixels.width, pixels.height);
const out = blank(side, side);
const left = (side - pixels.width) / 2;
const top = Math.floor((side - pixels.height) / 2);
for (let y = 0; y < pixels.height; y++) for (let x = 0; x < pixels.width; x++) copyPixel(pixels, x, y, out, left + x, top + y);
return out;
}
/** Rounds halves away from zero, so that a turn to the left mirrors a turn to the right. */
const round = (v: number) => Math.sign(v) * Math.floor(Math.abs(v) + 0.5);
/** A whole number of quarter turns and what is left, between -45 and 45 degrees. */
function split(degrees: number): { turns: number; rest: number } {
if (!Number.isFinite(degrees)) throw new Error(`An angle has to be a number of degrees, not ${degrees}.`);
const turns = round(degrees / 90);
return { turns, rest: degrees - turns * 90 };
}
/** The slanted part of a turn as three slides. `square` has room; `rest` is between -45 and 45 degrees. */
function slide(square: Pixels, rest: number): Pixels {
const side = square.width;
const middle = (side - 1) / 2;
const angle = (rest * Math.PI) / 180;
const sideways = -Math.tan(angle / 2);
const upDown = Math.sin(angle);
const out = blank(side, side);
for (let y = 0; y < side; y++) {
for (let x = 0; x < side; x++) {
if (square.data[(y * side + x) * 4 + 3] === 0) continue;
// three slides: the row, then the column the pixel is in by then, then its new row
const x1 = x + round(sideways * (y - middle));
const y1 = y + round(upDown * (x1 - middle));
const x2 = x1 + round(sideways * (y1 - middle));
if (x2 < 0 || y1 < 0 || x2 >= side || y1 >= side) throw new Error("A pixel left the square while turning. This should not happen: please report the sprite's size and the angle.");
copyPixel(square, x, y, out, x2, y1);
}
}
return out;
}
/** The picture three times as big, with its stairs smoothed and every pixel's own colour kept in the middle of its block. */
function triple(pixels: Pixels): Pixels {
const { width, height } = pixels;
const out = blank(width * 3, height * 3);
/** A pixel's colour as one number; everything see-through, and everything outside, counts as the same. */
const key = (x: number, y: number) => {
if (x < 0 || y < 0 || x >= width || y >= height) return 0;
const i = (y * width + x) * 4;
return pixels.data[i + 3] === 0 ? 0 : pixels.data[i] * 16777216 + pixels.data[i + 1] * 65536 + pixels.data[i + 2] * 256 + pixels.data[i + 3];
};
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const a = key(x - 1, y - 1);
const b = key(x, y - 1);
const c = key(x + 1, y - 1);
const d = key(x - 1, y);
const e = key(x, y);
const f = key(x + 1, y);
const g = key(x - 1, y + 1);
const h = key(x, y + 1);
const i = key(x + 1, y + 1);
// which neighbour each of the nine small pixels takes its colour from: [dx, dy], [0, 0] is the pixel itself
const from: [number, number][] = Array.from({ length: 9 }, () => [0, 0]);
if (b !== h && d !== f) {
if (d === b) from[0] = [-1, 0];
if ((d === b && e !== c) || (b === f && e !== a)) from[1] = [0, -1];
if (b === f) from[2] = [1, 0];
if ((d === b && e !== g) || (d === h && e !== a)) from[3] = [-1, 0];
if ((b === f && e !== i) || (h === f && e !== c)) from[5] = [1, 0];
if (d === h) from[6] = [-1, 0];
if ((d === h && e !== i) || (h === f && e !== g)) from[7] = [0, 1];
if (h === f) from[8] = [1, 0];
}
for (let n = 0; n < 9; n++) {
const sx = x + from[n][0];
const sy = y + from[n][1];
// a neighbour outside the picture is see-through: leave the small pixel clear
if (sx < 0 || sy < 0 || sx >= width || sy >= height) continue;
copyPixel(pixels, sx, sy, out, x * 3 + (n % 3), y * 3 + Math.floor(n / 3));
}
}
}
return out;
}
/** The slanted part of a turn, read from the square drawn `scale` times as big; scale 1 is the usual way. */
function sample(square: Pixels, rest: number, big: Pixels, scale: number): Pixels {
const side = square.width;
const middle = (side - 1) / 2;
const angle = (rest * Math.PI) / 180;
const cos = Math.cos(angle);
const sin = Math.sin(angle);
const out = blank(side, side);
for (let y = 0; y < side; y++) {
for (let x = 0; x < side; x++) {
// where this new pixel was before the turn, as a place inside the big picture
const fx = Math.floor((middle + (x - middle) * cos + (y - middle) * sin + 0.5) * scale);
const fy = Math.floor((middle - (x - middle) * sin + (y - middle) * cos + 0.5) * scale);
if (fx >= 0 && fy >= 0 && fx < big.width && fy < big.height) copyPixel(big, fx, fy, out, x, y);
}
}
return out;
}
/** The sprite turned clockwise by any angle, on a square with room for every angle. */
export function rotate(pixels: Pixels, degrees: number, way: Way = DEFAULTS.way as Way): Pixels {
if (!["keep", "smooth", "nearest"].includes(way)) throw new Error(`There are three ways to turn: "keep", "smooth" and "nearest", not "${way}".`);
const { turns, rest } = split(degrees);
const square = quarterTurns(withRoom(pixels), turns);
if (rest === 0) return square;
if (way === "keep") return slide(square, rest);
if (way === "nearest") return sample(square, rest, square, 1);
return sample(square, rest, triple(triple(square)), 9);
}
/** A full turn as pictures of one size, clockwise, the first one not turned. */
export function turnFrames(pixels: Pixels, frames: number = DEFAULTS.frames, way: Way = DEFAULTS.way as Way): Pixels[] {
if (!Number.isInteger(frames) || frames < 1) throw new Error(`A turn is cut into a whole number of pictures, at least 1, not ${frames}.`);
return Array.from({ length: frames }, (_, i) => rotate(pixels, (i * 360) / frames, way));
}
/** How many pixels of each colour a picture has, by colour as "#rrggbb" or "#rrggbbaa". */
export function countColors(pixels: Pixels): Record<string, number> {
const counts: Record<string, number> = {};
const two = (n: number) => n.toString(16).padStart(2, "0");
for (let i = 0; i < pixels.data.length; i += 4) {
const a = pixels.data[i + 3];
if (a === 0) continue;
const color = "#" + two(pixels.data[i]) + two(pixels.data[i + 1]) + two(pixels.data[i + 2]) + (a === 255 ? "" : two(a));
counts[color] = (counts[color] ?? 0) + 1;
}
return counts;
}
/** What a change did to the pixel counts: for each colour that has more or fewer pixels now, by how many. Empty when every pixel was kept. */
export function lostPixels(before: Pixels, after: Pixels): Record<string, number> {
const a = countColors(before);
const b = countColors(after);
const out: Record<string, number> = {};
for (const color of [...new Set([...Object.keys(a), ...Object.keys(b)])].sort()) {
const change = (b[color] ?? 0) - (a[color] ?? 0);
if (change !== 0) out[color] = change;
}
return out;
}
/** How long the outline is: the sides of drawn pixels that touch a see-through pixel or the picture's edge. A rougher edge is longer. */
export function outlineLength(pixels: Pixels): number {
const drawn = (x: number, y: number) => x >= 0 && y >= 0 && x < pixels.width && y < pixels.height && pixels.data[(y * pixels.width + x) * 4 + 3] !== 0;
let sides = 0;
for (let y = 0; y < pixels.height; y++) {
for (let x = 0; x < pixels.width; x++) {
if (!drawn(x, y)) continue;
for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) if (!drawn(x + dx, y + dy)) sides++;
}
}
return sides;
}
```
Use the pixel rotation recipe from Spielerando. Turn my sprite into 8 frames in each of its three ways, show me the three rows side by side scaled up, and under each frame show me what the count of lost pixels says. I will pick the row.Settings
- frames (8): How many pictures a full turn is cut into. 8 gives one every 45 degrees, 16 one every 22.5.
- way (keep): How a slanted turn is done: keep for every pixel kept, smooth for the cleanest outline, nearest for what most engines do.
The code
Tested TypeScript with no outside parts. Copy it into your game, or hand it to your AI together with the text above.
/* Pixel rotation: turns a small sprite to any angle in three ways, and counts what each way did to
its pixels. No way of turning pixel art by a slanted angle is perfect, so the honest answer is
to make all three, look at them and read the counts.
Usage:
const turned = rotate(sprite, 30); // 30 degrees clockwise, every pixel kept
const smooth = rotate(sprite, 30, "smooth"); // cleaner outlines, small details may go
const usual = rotate(sprite, 30, "nearest"); // what most game engines do
lostPixels(sprite, usual); // { "#1f2142": -3 }: three dark pixels fewer
lostPixels(sprite, turned); // {}: nothing lost, nothing doubled
outlineLength(smooth); // a rougher edge is a longer one
const frames = turnFrames(sprite, 8); // a full turn in 8 pictures, all one size
const left = mirror(sprite); // facing the other way
const up = quarterTurns(sprite, -1); // a quarter turn against the clock, exact
`sprite` is { width, height, data } with four numbers a pixel (red, green, blue, opacity), the
shape a canvas uses.
The three ways:
"keep" A turn done as three slides: every row slides sideways by whole pixels, then
every column up or down, then every row again. A slide by whole pixels cannot
lose or double a pixel, so an eye of one pixel never vanishes. The price: each
pixel may land about one pixel off the perfect place, so edges get rougher,
most of all near 45 degrees.
"smooth" The sprite is first drawn nine times as big with its stairs smoothed, and the
turned picture is read from that. Outlines come out cleanest. The price: parts
that are one pixel thin can go missing or change size.
"nearest" Each new pixel takes the old pixel nearest to where it came from. Some old
pixels are then taken twice and some never. It is here to compare against.
Quarter turns and mirroring are exact in every way, and are done first, so only the last 45
degrees or less are ever slanted.
Always turn the original sprite, never one that was turned before, or the damage adds up. The
turned picture sits on a square that is big enough for every angle, and the sprite turns
around the square's middle. To turn around another point, a sword around its handle, say, put
the sprite on a bigger see-through picture first so that this point is the middle.
SPDX-License-Identifier: MIT
Copyright (c) 2026 Spielerando, https://spielerando.com */
export const DEFAULTS = {
/** How many pictures a full turn is cut into: 8 gives one every 45 degrees. */
frames: 8,
/** How a slanted turn is done: "keep" every pixel, "smooth" outlines, or "nearest", the usual way. */
way: "keep",
};
export type Way = "keep" | "smooth" | "nearest";
/** A picture as a canvas holds it: four numbers a pixel (red, green, blue, opacity), row by row. */
export interface Pixels {
width: number;
height: number;
data: Uint8ClampedArray;
}
const blank = (width: number, height: number): Pixels => ({ width, height, data: new Uint8ClampedArray(width * height * 4) });
function copyPixel(from: Pixels, fx: number, fy: number, to: Pixels, tx: number, ty: number): void {
const a = (fy * from.width + fx) * 4;
const b = (ty * to.width + tx) * 4;
to.data[b] = from.data[a];
to.data[b + 1] = from.data[a + 1];
to.data[b + 2] = from.data[a + 2];
to.data[b + 3] = from.data[a + 3];
}
/** The picture facing the other way, or stood on its head. */
export function mirror(pixels: Pixels, direction: "sideways" | "upside-down" = "sideways"): Pixels {
const out = blank(pixels.width, pixels.height);
for (let y = 0; y < pixels.height; y++) {
for (let x = 0; x < pixels.width; x++) {
if (direction === "sideways") copyPixel(pixels, x, y, out, pixels.width - 1 - x, y);
else copyPixel(pixels, x, y, out, x, pixels.height - 1 - y);
}
}
return out;
}
/** The picture turned by quarter turns, clockwise for positive numbers. Exact: no pixel changes, only its place. */
export function quarterTurns(pixels: Pixels, turns: number): Pixels {
if (!Number.isInteger(turns)) throw new Error(`Quarter turns come in whole numbers, not ${turns}. For any other angle use rotate.`);
const n = ((turns % 4) + 4) % 4;
const out = n % 2 === 1 ? blank(pixels.height, pixels.width) : blank(pixels.width, pixels.height);
for (let y = 0; y < pixels.height; y++) {
for (let x = 0; x < pixels.width; x++) {
if (n === 0) copyPixel(pixels, x, y, out, x, y);
else if (n === 1) copyPixel(pixels, x, y, out, pixels.height - 1 - y, x);
else if (n === 2) copyPixel(pixels, x, y, out, pixels.width - 1 - x, pixels.height - 1 - y);
else copyPixel(pixels, x, y, out, y, pixels.width - 1 - x);
}
}
return out;
}
/** The side of the square a sprite of this size is turned on: room for every angle. */
export function roomFor(width: number, height: number): number {
let side = 2 * Math.ceil(Math.hypot(width, height) / 2 + 2);
// the sprite sits exactly in the middle from left to right
if ((side - width) % 2 !== 0) side++;
return side;
}
/** The sprite in the middle of a see-through square with room to turn. */
function withRoom(pixels: Pixels): Pixels {
const side = roomFor(pixels.width, pixels.height);
const out = blank(side, side);
const left = (side - pixels.width) / 2;
const top = Math.floor((side - pixels.height) / 2);
for (let y = 0; y < pixels.height; y++) for (let x = 0; x < pixels.width; x++) copyPixel(pixels, x, y, out, left + x, top + y);
return out;
}
/** Rounds halves away from zero, so that a turn to the left mirrors a turn to the right. */
const round = (v: number) => Math.sign(v) * Math.floor(Math.abs(v) + 0.5);
/** A whole number of quarter turns and what is left, between -45 and 45 degrees. */
function split(degrees: number): { turns: number; rest: number } {
if (!Number.isFinite(degrees)) throw new Error(`An angle has to be a number of degrees, not ${degrees}.`);
const turns = round(degrees / 90);
return { turns, rest: degrees - turns * 90 };
}
/** The slanted part of a turn as three slides. `square` has room; `rest` is between -45 and 45 degrees. */
function slide(square: Pixels, rest: number): Pixels {
const side = square.width;
const middle = (side - 1) / 2;
const angle = (rest * Math.PI) / 180;
const sideways = -Math.tan(angle / 2);
const upDown = Math.sin(angle);
const out = blank(side, side);
for (let y = 0; y < side; y++) {
for (let x = 0; x < side; x++) {
if (square.data[(y * side + x) * 4 + 3] === 0) continue;
// three slides: the row, then the column the pixel is in by then, then its new row
const x1 = x + round(sideways * (y - middle));
const y1 = y + round(upDown * (x1 - middle));
const x2 = x1 + round(sideways * (y1 - middle));
if (x2 < 0 || y1 < 0 || x2 >= side || y1 >= side) throw new Error("A pixel left the square while turning. This should not happen: please report the sprite's size and the angle.");
copyPixel(square, x, y, out, x2, y1);
}
}
return out;
}
/** The picture three times as big, with its stairs smoothed and every pixel's own colour kept in the middle of its block. */
function triple(pixels: Pixels): Pixels {
const { width, height } = pixels;
const out = blank(width * 3, height * 3);
/** A pixel's colour as one number; everything see-through, and everything outside, counts as the same. */
const key = (x: number, y: number) => {
if (x < 0 || y < 0 || x >= width || y >= height) return 0;
const i = (y * width + x) * 4;
return pixels.data[i + 3] === 0 ? 0 : pixels.data[i] * 16777216 + pixels.data[i + 1] * 65536 + pixels.data[i + 2] * 256 + pixels.data[i + 3];
};
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const a = key(x - 1, y - 1);
const b = key(x, y - 1);
const c = key(x + 1, y - 1);
const d = key(x - 1, y);
const e = key(x, y);
const f = key(x + 1, y);
const g = key(x - 1, y + 1);
const h = key(x, y + 1);
const i = key(x + 1, y + 1);
// which neighbour each of the nine small pixels takes its colour from: [dx, dy], [0, 0] is the pixel itself
const from: [number, number][] = Array.from({ length: 9 }, () => [0, 0]);
if (b !== h && d !== f) {
if (d === b) from[0] = [-1, 0];
if ((d === b && e !== c) || (b === f && e !== a)) from[1] = [0, -1];
if (b === f) from[2] = [1, 0];
if ((d === b && e !== g) || (d === h && e !== a)) from[3] = [-1, 0];
if ((b === f && e !== i) || (h === f && e !== c)) from[5] = [1, 0];
if (d === h) from[6] = [-1, 0];
if ((d === h && e !== i) || (h === f && e !== g)) from[7] = [0, 1];
if (h === f) from[8] = [1, 0];
}
for (let n = 0; n < 9; n++) {
const sx = x + from[n][0];
const sy = y + from[n][1];
// a neighbour outside the picture is see-through: leave the small pixel clear
if (sx < 0 || sy < 0 || sx >= width || sy >= height) continue;
copyPixel(pixels, sx, sy, out, x * 3 + (n % 3), y * 3 + Math.floor(n / 3));
}
}
}
return out;
}
/** The slanted part of a turn, read from the square drawn `scale` times as big; scale 1 is the usual way. */
function sample(square: Pixels, rest: number, big: Pixels, scale: number): Pixels {
const side = square.width;
const middle = (side - 1) / 2;
const angle = (rest * Math.PI) / 180;
const cos = Math.cos(angle);
const sin = Math.sin(angle);
const out = blank(side, side);
for (let y = 0; y < side; y++) {
for (let x = 0; x < side; x++) {
// where this new pixel was before the turn, as a place inside the big picture
const fx = Math.floor((middle + (x - middle) * cos + (y - middle) * sin + 0.5) * scale);
const fy = Math.floor((middle - (x - middle) * sin + (y - middle) * cos + 0.5) * scale);
if (fx >= 0 && fy >= 0 && fx < big.width && fy < big.height) copyPixel(big, fx, fy, out, x, y);
}
}
return out;
}
/** The sprite turned clockwise by any angle, on a square with room for every angle. */
export function rotate(pixels: Pixels, degrees: number, way: Way = DEFAULTS.way as Way): Pixels {
if (!["keep", "smooth", "nearest"].includes(way)) throw new Error(`There are three ways to turn: "keep", "smooth" and "nearest", not "${way}".`);
const { turns, rest } = split(degrees);
const square = quarterTurns(withRoom(pixels), turns);
if (rest === 0) return square;
if (way === "keep") return slide(square, rest);
if (way === "nearest") return sample(square, rest, square, 1);
return sample(square, rest, triple(triple(square)), 9);
}
/** A full turn as pictures of one size, clockwise, the first one not turned. */
export function turnFrames(pixels: Pixels, frames: number = DEFAULTS.frames, way: Way = DEFAULTS.way as Way): Pixels[] {
if (!Number.isInteger(frames) || frames < 1) throw new Error(`A turn is cut into a whole number of pictures, at least 1, not ${frames}.`);
return Array.from({ length: frames }, (_, i) => rotate(pixels, (i * 360) / frames, way));
}
/** How many pixels of each colour a picture has, by colour as "#rrggbb" or "#rrggbbaa". */
export function countColors(pixels: Pixels): Record<string, number> {
const counts: Record<string, number> = {};
const two = (n: number) => n.toString(16).padStart(2, "0");
for (let i = 0; i < pixels.data.length; i += 4) {
const a = pixels.data[i + 3];
if (a === 0) continue;
const color = "#" + two(pixels.data[i]) + two(pixels.data[i + 1]) + two(pixels.data[i + 2]) + (a === 255 ? "" : two(a));
counts[color] = (counts[color] ?? 0) + 1;
}
return counts;
}
/** What a change did to the pixel counts: for each colour that has more or fewer pixels now, by how many. Empty when every pixel was kept. */
export function lostPixels(before: Pixels, after: Pixels): Record<string, number> {
const a = countColors(before);
const b = countColors(after);
const out: Record<string, number> = {};
for (const color of [...new Set([...Object.keys(a), ...Object.keys(b)])].sort()) {
const change = (b[color] ?? 0) - (a[color] ?? 0);
if (change !== 0) out[color] = change;
}
return out;
}
/** How long the outline is: the sides of drawn pixels that touch a see-through pixel or the picture's edge. A rougher edge is longer. */
export function outlineLength(pixels: Pixels): number {
const drawn = (x: number, y: number) => x >= 0 && y >= 0 && x < pixels.width && y < pixels.height && pixels.data[(y * pixels.width + x) * 4 + 3] !== 0;
let sides = 0;
for (let y = 0; y < pixels.height; y++) {
for (let x = 0; x < pixels.width; x++) {
if (!drawn(x, y)) continue;
for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) if (!drawn(x + dx, y + dy)) sides++;
}
}
return sides;
}
The tests this code passes
import assert from "node:assert/strict";
import test from "node:test";
import { DEFAULTS, type Pixels, type Way, countColors, lostPixels, mirror, outlineLength, quarterTurns, roomFor, rotate, turnFrames } from "./code.ts";
const COLORS: Record<string, number[]> = { k: [0x1f, 0x21, 0x42, 255], w: [255, 255, 255, 255], y: [0xf2, 0xc1, 0x4e, 255], r: [0xc2, 0x41, 0x2d, 255], g: [0x0f, 0x8a, 0x4c, 128] };
/** A picture from rows of letters; a dot is see-through. */
function draw(rows: string[]): Pixels {
const width = rows[0].length;
const data = new Uint8ClampedArray(width * rows.length * 4);
rows.forEach((row, y) => [...row].forEach((letter, x) => letter !== "." && data.set(COLORS[letter], (y * width + x) * 4)));
return { width, height: rows.length, data };
}
/** An arrow with thin parts: a one-pixel shaft, two white eyes, a half see-through tail. */
const ARROW = draw([
"....k....",
"...kyk...",
"..kwywk..",
".k..y..k.",
"....y....",
"....y....",
"...ryr...",
"....g....",
]);
const at = (p: Pixels, x: number, y: number) => [...p.data.slice((y * p.width + x) * 4, (y * p.width + x) * 4 + 4)];
const where = (p: Pixels, color: number[]) => {
const found: number[][] = [];
for (let y = 0; y < p.height; y++) for (let x = 0; x < p.width; x++) if (at(p, x, y).join() === color.join()) found.push([x, y]);
return found;
};
function random(seed: number) {
let s = seed >>> 0;
return () => {
s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
return s / 4294967296;
};
}
test("mirroring swaps left and right, or top and bottom, and twice gives the picture back", () => {
const p = draw(["kw.", "..y"]);
assert.deepEqual(mirror(p), draw([".wk", "y.."]));
assert.deepEqual(mirror(p, "upside-down"), draw(["..y", "kw."]));
assert.deepEqual(mirror(mirror(ARROW)), ARROW);
assert.deepEqual(mirror(mirror(ARROW, "upside-down"), "upside-down"), ARROW);
assert.deepEqual(countColors(mirror(ARROW)), countColors(ARROW));
});
test("quarter turns are exact: clockwise for positive numbers, and four make a full turn", () => {
const p = draw(["kw.", "..y"]);
assert.deepEqual(quarterTurns(p, 1), draw([".k", ".w", "y."]));
assert.deepEqual(quarterTurns(p, 2), draw(["y..", ".wk"]));
assert.deepEqual(quarterTurns(p, 3), draw([".y", "w.", "k."]));
assert.deepEqual(quarterTurns(p, -1), quarterTurns(p, 3));
assert.deepEqual(quarterTurns(p, 4), p);
assert.deepEqual(quarterTurns(p, 0), p);
assert.deepEqual(quarterTurns(quarterTurns(ARROW, 1), -1), ARROW);
assert.deepEqual(quarterTurns(ARROW, 2), mirror(mirror(ARROW), "upside-down"));
assert.throws(() => quarterTurns(p, 0.5), /whole numbers/);
});
test("a turn by any whole degree keeps every pixel of every colour", () => {
const before = countColors(ARROW);
assert.deepEqual(before, { "#0f8a4c80": 1, "#1f2142": 7, "#c2412d": 2, "#f2c14e": 6, "#ffffff": 2 });
for (let degrees = -360; degrees <= 720; degrees++) {
const turned = rotate(ARROW, degrees);
assert.deepEqual(countColors(turned), before, `${degrees} degrees`);
assert.deepEqual(lostPixels(ARROW, turned), {}, `${degrees} degrees`);
}
for (const degrees of [0.5, 22.5, 44.999, 45, 45.001, 89.9, 133.7]) assert.deepEqual(lostPixels(ARROW, rotate(ARROW, degrees)), {}, `${degrees} degrees`);
});
test("it holds for sprites of any size, full or sparse", () => {
const next = random(7);
for (const [width, height] of [[1, 1], [2, 1], [1, 7], [3, 5], [8, 8], [16, 16], [17, 9], [32, 32]]) {
for (const fill of [1, 0.5, 0.1]) {
const data = new Uint8ClampedArray(width * height * 4);
for (let i = 0; i < width * height; i++) if (next() < fill) data.set([Math.floor(next() * 4) * 60, 30, 200, 255], i * 4);
const sprite = { width, height, data };
for (let i = 0; i < 40; i++) {
const degrees = Math.round(next() * 7200) / 10 - 360;
assert.deepEqual(lostPixels(sprite, rotate(sprite, degrees)), {}, `${width} by ${height}, ${degrees} degrees`);
}
}
}
});
test("every angle gives a square of the same size, with the sprite in the middle when it is not turned", () => {
// half the diagonal, two pixels of room, and one more so that 9 columns sit exactly in the middle
assert.equal(roomFor(9, 8), 19);
assert.equal(roomFor(16, 16), 28);
assert.equal(roomFor(32, 32), 50);
for (let degrees = 0; degrees < 360; degrees += 7) {
const turned = rotate(ARROW, degrees);
assert.deepEqual([turned.width, turned.height], [19, 19], `${degrees} degrees`);
}
const still = rotate(ARROW, 0);
// 9 wide on 19: five clear columns on each side; 8 high on 19: five clear rows above, six below
for (let y = 0; y < 8; y++) for (let x = 0; x < 9; x++) assert.deepEqual(at(still, x + 5, y + 5), at(ARROW, x, y));
assert.equal(Object.values(countColors(still)).reduce((a, b) => a + b), 18);
assert.deepEqual(rotate(ARROW, 360), still);
assert.deepEqual(rotate(ARROW, -720), still);
});
test("positive angles turn clockwise, and the quarter turns among them are exact", () => {
const still = rotate(ARROW, 0);
assert.deepEqual(rotate(ARROW, 90), quarterTurns(still, 1));
assert.deepEqual(rotate(ARROW, 180), quarterTurns(still, 2));
assert.deepEqual(rotate(ARROW, 270), quarterTurns(still, 3));
assert.deepEqual(rotate(ARROW, -90), quarterTurns(still, -1));
// the arrow points up and its green tail is straight below the middle; clockwise, the tail swings to the left
const tail = [0x0f, 0x8a, 0x4c, 128];
const middle = 9;
assert.deepEqual(where(still, tail), [[9, 12]]);
assert.deepEqual(where(rotate(ARROW, 90), tail), [[6, 9]]);
const [[x45, y45]] = where(rotate(ARROW, 45), tail);
assert.ok(x45 < middle && y45 > middle, `at 45 degrees the tail is down left, at ${x45}, ${y45}`);
const [[xBack, yBack]] = where(rotate(ARROW, -45), tail);
assert.ok(xBack > middle && yBack > middle, `at 45 degrees against the clock it is down right, at ${xBack}, ${yBack}`);
assert.deepEqual([xBack, yBack], [18 - x45, y45]);
});
test("each pixel lands close to the perfect place: less than 1.2 pixels away", () => {
let worst = 0;
for (const [width, height] of [[1, 1], [3, 5], [8, 8], [16, 16], [17, 9], [32, 32]]) {
const side = roomFor(width, height);
const left = (side - width) / 2;
const top = Math.floor((side - height) / 2);
const middle = (side - 1) / 2;
// each pixel gets a colour of its own, so that it can be found again after the turn
const data = new Uint8ClampedArray(width * height * 4);
for (let i = 0; i < width * height; i++) data.set([i & 255, i >> 8, 7, 255], i * 4);
for (let degrees = 0; degrees < 360; degrees++) {
const turned = rotate({ width, height, data }, degrees);
const angle = (degrees * Math.PI) / 180;
let found = 0;
for (let y = 0; y < side; y++) {
for (let x = 0; x < side; x++) {
const k = (y * side + x) * 4;
if (turned.data[k + 3] === 0) continue;
found++;
const i = turned.data[k] | (turned.data[k + 1] << 8);
const fromX = left + (i % width) - middle;
const fromY = top + Math.floor(i / width) - middle;
const perfectX = fromX * Math.cos(angle) - fromY * Math.sin(angle);
const perfectY = fromX * Math.sin(angle) + fromY * Math.cos(angle);
worst = Math.max(worst, Math.hypot(x - middle - perfectX, y - middle - perfectY));
}
}
assert.equal(found, width * height, `${width} by ${height}, ${degrees} degrees`);
}
}
assert.ok(worst < 1.2, `the farthest was ${worst}`);
assert.ok(worst > 0.9, "and the bound is not much too wide");
});
test("a turn to the left is the mirror image of a turn to the right", () => {
for (const degrees of [1, 10, 30, 44, 45, 46, 77, 135, 200.5]) {
assert.deepEqual(rotate(mirror(ARROW), -degrees), mirror(rotate(ARROW, degrees)), `${degrees} degrees`);
}
});
test("the other two ways lose and double pixels, and lostPixels shows which", () => {
assert.equal(DEFAULTS.way, "keep");
assert.deepEqual(rotate(ARROW, 30), rotate(ARROW, 30, "keep"));
assert.deepEqual(lostPixels(ARROW, rotate(ARROW, 30)), {});
assert.notDeepEqual(lostPixels(ARROW, rotate(ARROW, 30, "nearest")), {});
assert.notDeepEqual(lostPixels(ARROW, rotate(ARROW, 30, "smooth")), {});
// over a full turn in whole degrees: how often a count changes, and how often a white eye is lost
const tally = (way: Way) => {
let changed = 0;
let eyeLost = 0;
for (let degrees = 0; degrees < 360; degrees++) {
const lost = lostPixels(ARROW, rotate(ARROW, degrees, way));
if (Object.keys(lost).length > 0) changed++;
if ((lost["#ffffff"] ?? 0) < 0) eyeLost++;
}
return { changed, eyeLost };
};
assert.deepEqual(tally("keep"), { changed: 0, eyeLost: 0 });
const nearest = tally("nearest");
const smooth = tally("smooth");
assert.ok(nearest.changed > 180, `the usual way changed a count at ${nearest.changed} of 360 angles`);
assert.ok(nearest.eyeLost > 0, `it lost a white eye at ${nearest.eyeLost} angles`);
assert.ok(smooth.changed > nearest.changed, `the smooth way changed a count at ${smooth.changed} angles`);
assert.ok(smooth.eyeLost > nearest.eyeLost, `it lost a white eye at ${smooth.eyeLost} angles`);
});
test("every way is exact at quarter turns, and never makes up a colour", () => {
const colors = Object.keys(countColors(ARROW));
for (const way of ["keep", "smooth", "nearest"] as const) {
for (const degrees of [0, 90, 180, 270, -90, 360]) assert.deepEqual(rotate(ARROW, degrees, way), rotate(ARROW, degrees, "keep"), `${way}, ${degrees} degrees`);
for (let degrees = 0; degrees < 360; degrees += 3) {
const turned = rotate(ARROW, degrees, way);
assert.deepEqual([turned.width, turned.height], [19, 19]);
for (const color of Object.keys(countColors(turned))) assert.ok(colors.includes(color), `${way}, ${degrees} degrees: ${color}`);
}
}
assert.throws(() => rotate(ARROW, 30, "bicubic" as Way), /three ways to turn/);
});
test("the smooth way gives the shortest outline of the three", () => {
// a filled square of 12 pixels a side: 48 pixel sides of outline, 144 pixels
const square: Pixels = { width: 12, height: 12, data: new Uint8ClampedArray(12 * 12 * 4).fill(255) };
assert.equal(outlineLength(square), 48);
// one pixel has four sides showing, two side by side six, an L of three eight
assert.equal(outlineLength(draw(["k"])), 4);
assert.equal(outlineLength(draw(["kk"])), 6);
assert.equal(outlineLength(draw(["k.", "kk"])), 8);
const average = (sprite: Pixels, way: Way) => {
let total = 0;
for (let degrees = 0; degrees < 360; degrees++) total += outlineLength(rotate(sprite, degrees, way));
return total / 360;
};
for (const sprite of [square, ARROW]) {
const keep = average(sprite, "keep");
const nearest = average(sprite, "nearest");
const smooth = average(sprite, "smooth");
assert.ok(smooth < nearest && smooth < keep, `smooth ${smooth}, nearest ${nearest}, keep ${keep}`);
}
// the square stays close to its size in the two ways that may change it
for (const way of ["smooth", "nearest"] as const) {
for (let degrees = 0; degrees < 360; degrees++) {
const area = Object.values(countColors(rotate(square, degrees, way))).reduce((a, b) => a + b, 0);
assert.ok(area >= 136 && area <= 148, `${way}, ${degrees} degrees: ${area} pixels`);
}
}
});
test("a full turn comes as pictures of one size, the first not turned, the quarters exact", () => {
assert.equal(DEFAULTS.frames, 8);
const frames = turnFrames(ARROW);
assert.equal(frames.length, 8);
assert.deepEqual(frames[0], rotate(ARROW, 0));
frames.forEach((frame, i) => {
assert.deepEqual([frame.width, frame.height], [19, 19]);
assert.deepEqual(frame, rotate(ARROW, i * 45));
assert.deepEqual(countColors(frame), countColors(ARROW));
});
assert.deepEqual(frames[2], quarterTurns(frames[0], 1));
assert.deepEqual(frames[4], quarterTurns(frames[0], 2));
assert.equal(turnFrames(ARROW, 12).length, 12);
assert.deepEqual(turnFrames(ARROW, 8, "smooth")[1], rotate(ARROW, 45, "smooth"));
assert.deepEqual(turnFrames(ARROW, 1), [frames[0]]);
for (const bad of [0, 2.5, -4]) assert.throws(() => turnFrames(ARROW, bad), /whole number of pictures/);
});
test("what is not an angle is refused", () => {
for (const bad of [Number.NaN, Number.POSITIVE_INFINITY]) {
for (const way of ["keep", "smooth", "nearest"] as const) assert.throws(() => rotate(ARROW, bad, way), /number of degrees/);
}
});
Common questions
why does my pixel art look broken when i rotate it
A slanted turn cannot put every pixel back on the grid, so the usual way drops some pixels and doubles others. Thin lines break and details of one pixel disappear. Turning in three slides of whole pixels keeps them all.
how do i rotate a sprite without losing pixels
Do quarter turns exactly, then do the rest as three slides: rows sideways, columns up or down, rows again, each by whole pixels. No slide can lose a pixel, so the whole turn cannot.
should i rotate sprites in the engine or make frames
For soft or large art the engine's own turning is fine. For small pixel art, make the frames once from the original, look at them, and fix single pixels where needed, because the usual way changes which pixels a sprite has from one angle to the next.
Was this page helpful?
Next step
Code recipe
Pixel art from text
- Or: Sprite sheet check
- Or: Sprite stack