pixeltation/src/engine/PixelCanvas.ts

51 lines
1.6 KiB
TypeScript

import { Surface } from './Surface';
/**
* Presents a low-res Surface on a <canvas>, scaled up by the largest whole number of
* device pixels that fits the parent so pixels stay perfectly square and crisp.
*/
export class PixelCanvas {
readonly canvas: HTMLCanvasElement;
readonly surface: Surface;
private readonly ctx: CanvasRenderingContext2D;
private readonly image: ImageData;
constructor(
private readonly parent: HTMLElement,
w = 320,
h = 180,
) {
this.canvas = document.createElement('canvas');
this.canvas.width = w;
this.canvas.height = h;
this.canvas.className = 'pixel-canvas';
this.ctx = this.canvas.getContext('2d')!;
this.surface = new Surface(w, h);
this.image = new ImageData(this.surface.data, w, h);
parent.appendChild(this.canvas);
window.addEventListener('resize', this.resize);
document.addEventListener('fullscreenchange', this.resize);
this.resize();
}
resize = (): void => {
const { w, h } = this.surface;
const dpr = window.devicePixelRatio || 1;
const fit = Math.min(this.parent.clientWidth / w, this.parent.clientHeight / h) * dpr;
// Whole-number scaling keeps every art pixel the same size; tiny screens fall back to a plain fit.
const scale = fit >= 2 ? Math.floor(fit) : fit;
this.canvas.style.width = `${(w * scale) / dpr}px`;
this.canvas.style.height = `${(h * scale) / dpr}px`;
};
present(): void {
this.ctx.putImageData(this.image, 0, 0);
}
destroy(): void {
window.removeEventListener('resize', this.resize);
document.removeEventListener('fullscreenchange', this.resize);
this.canvas.remove();
}
}