render-canvas.ts

73 lines | 2.223 kB Blame History Raw Download
import { BaseElement } from '../../../shared/_base';
import './render-canvas.less';

export class RenderCanvas extends BaseElement {
    public canvas: HTMLCanvasElement | null = null;
    public ctx: CanvasRenderingContext2D | null = null;
    public width: number = 0;
    public height: number = 0;
    public units = {
        width: 400,
        heigt: 400
    }

    onInit(): void {
        this.canvas = document.createElement("canvas");
        this.ctx = <CanvasRenderingContext2D>this.canvas.getContext("2d");
        this.appendChild(this.canvas);

        window.addEventListener("resize", () => {
            this.handleCanvasResize();
        });

        this.handleCanvasResize();
    }

    private handleCanvasResize() {
        if (this.parentElement && this.canvas) {
            this.width = this.parentElement.clientWidth;
            this.height = this.parentElement.clientHeight;

            this.canvas.style.width = this.width + "px";
            this.canvas.style.height = this.width + "px";
            this.canvas.setAttribute("width", this.width.toString());
            this.canvas.setAttribute("height", this.width.toString());
        }
    }

    drawPoly(points: { x: number, y: number }[]) {
        if (this.ctx) {
            this.ctx.fillStyle = "rgba(0,0,0,0)";
            this.ctx.strokeStyle = "rgba(0,0,0,1)";
            this.ctx.beginPath();

            for (var i = 0; i < points.length; i++) {
                var point = points[i];

                if (i === 0) {
                    this.ctx.moveTo(this.unitsToPx(point.x), this.unitsToPx(point.y));
                }
                else {
                    this.ctx.lineTo(this.unitsToPx(point.x), this.unitsToPx(point.y));
                }
            }

            this.ctx.closePath();
            this.ctx.fill();
            this.ctx.stroke();
        }
    }

    drawRect(x: number, y: number, width: number, height: number) {
        this.drawPoly([{ x: x, y: y }, { x: x + width, y: y }, { x: x + width, y: y + height }, { x: x, y: y + height }]);
    }

    unitsToPx(unitNumber: number) {
        var newPPU = (this.width / this.units.width);
        return unitNumber * newPPU;
    }

    onUpdate(): void {
        console.log("APP ROOT UPDATE");
    }
}