render-canvas.ts
Home
/
outputframe-app /
elements /
render-canvas /
render-canvas.ts
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
}
public prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");
onInit(): void {
this.canvas = document.createElement("canvas");
this.ctx = <CanvasRenderingContext2D>this.canvas.getContext("2d");
this.appendChild(this.canvas);
this.canvas.style.display = "none";
window.addEventListener("resize", () => {
this.handleCanvasResize();
});
this.handleCanvasResize();
}
private handleCanvasResize() {
if (this.parentElement && this.canvas) {
this.width = this.parentElement.clientWidth - 20;
this.height = this.parentElement.clientHeight - 20;
var smallest = Math.min(this.width, this.height);
this.canvas.style.width = smallest + "px";
this.canvas.style.height = smallest + "px";
this.canvas.setAttribute("width", smallest.toString());
this.canvas.setAttribute("height", smallest.toString());
}
}
drawPoly(points: { x: number, y: number }[]) {
if (this.ctx && this.canvas) {
this.canvas.style.display = "block";
this.ctx.fillStyle = "rgba(0,0,0,0)";
this.ctx.strokeStyle = this.getColor();
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();
}
}
getColor() {
return this.prefersDarkScheme.matches ? 'rgba(255,255,255,1)' : 'rgba(0,0,0,1)';
}
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 = Math.min(this.width, this.height) / this.units.width;
return unitNumber * newPPU;
}
onUpdate(): void {
console.log("APP ROOT UPDATE");
}
}