CanvasOption.ts
export default class CanvasOption {
canvas: HTMLCanvasElement = document.querySelector("canvas") as HTMLCanvasElement;
ctx: CanvasRenderingContext2D = this.canvas.getContext("2d")!;
dpr: number = window.devicePixelRatio;
fps: number = 60;
interval: number = 1000 / this.fps;
canvasWidth: number = innerWidth;
canvasHeight: number = innerHeight;
};
Canvas.ts
import CanvasOption from "./CanvasOption";
export default class Canvas extends CanvasOption {
constructor() {
super();
}
init = () => {
this.canvasWidth = innerWidth;
this.canvasHeight = innerHeight;
this.canvas.width = this.canvasWidth * this.dpr;
this.canvas.height = this.canvasHeight * this.dpr;
this.ctx.scale(this.dpr, this.dpr);
this.canvas.style.width = this.canvasWidth + "px";
this.canvas.style.height = this.canvasHeight + "px";
};
render = () => {
let now: number, delta: number;
let then = Date.now();
const frame = () => {
requestAnimationFrame(frame);
now = Date.now();
delta = now - then;
if( delta < this.interval ) return;
this.ctx.fillRect(100, 100, 300, 200);
then = now - (delta % this.interval);
};
requestAnimationFrame(frame);
}
};
index.ts
import Canvas from "./Model/Canvas";
const canvas = new Canvas();
window.addEventListener("load", () => {
canvas.init();
canvas.render();
});
window.addEventListener("resize", () => {
canvas.init();
});