Canvas boiler code

강정우·2024년 4월 13일
0

HTML, CSS

목록 보기
27/27

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();
});
profile
智(지)! 德(덕)! 體(체)!

0개의 댓글