Fix background and fix PageElement system

This commit is contained in:
schmelczerandras 2020-11-22 22:41:10 +01:00
parent 6fc16f4de0
commit 91d92f7f48
24 changed files with 528 additions and 809 deletions

View file

@ -1,30 +0,0 @@
export class Animation<T> {
private _value: T;
private elapsedTime = 0;
public constructor(
private from: T,
private to: T,
private intervalInMs: number,
private interpolator: (from: T, to: T, q: number) => T,
private onChange?: (currentValue: T) => void
) {
this._value = from;
}
public step(deltaTimeInMs: number) {
if (this.elapsedTime === this.intervalInMs) {
return;
}
this.elapsedTime = Math.min(this.elapsedTime + deltaTimeInMs, this.intervalInMs);
const q = this.elapsedTime / this.intervalInMs;
this._value = this.interpolator(this.from, this.to, q);
this.onChange?.call(null, this._value);
}
public get value(): T {
return this._value;
}
}

View file

@ -2,5 +2,5 @@ import './background.scss';
import { html } from '../../types/html';
export const generate = (): html => `
<canvas id="background"></canvas>
<div id="background"></div>
`;

View file

@ -1,12 +1,20 @@
@use '../../style/mixins' as *;
@use '../../style/dark-mode/dark-mode' as *;
canvas#background {
position: fixed;
top: 0;
.blob {
position: absolute;
left: 0;
height: 100%;
width: 100%;
z-index: -10;
top: 0;
border-radius: 1000px;
transition: background-color var(--transition-time);
&:nth-child(odd) {
background-color: #fff9e0;
}
&:nth-child(even) {
background-color: #ffd6d6;
}
@media print {
& {
@ -14,3 +22,9 @@ canvas#background {
}
}
}
@include in-dark-mode {
.blob {
background-color: #2c477a;
}
}

View file

@ -1,160 +1,121 @@
import { PageElement } from '../page-element';
import { Blob } from './blob';
import { generate } from './background.html';
import { Vec3 } from './vec3';
import { Vec2 } from './vec2';
import { createElement } from '../../helper/create-element';
import { sum } from '../../helper/sum';
import { getHeight } from '../../helper/get-height';
import { OnLoadEvent } from '../../events/concrete-events/on-load-event';
import { OptionalEvent } from '../../events/optional-event';
import { OnPageThemeChangedEvent } from '../../events/concrete-events/on-page-theme-changed-event';
import { mix } from '../../helper/mix';
import { Random } from '../../helper/random';
export class PageBackground extends PageElement {
public static readonly blobSpacing = 325;
public static readonly minBlobCount = 30;
public static readonly perspective = 5;
public static readonly zMin = 10;
public static readonly zMax = 30;
private static readonly perspective = 5;
private static readonly zMin = 6;
private static readonly zMax = 50;
private backgroundSize: Vec2;
private scrollPosition = 0;
private previousTimestamp: DOMHighResTimeStamp = null;
private readonly blobs: Array<Blob> = [];
private readonly canvas: HTMLCanvasElement;
private readonly ctx: CanvasRenderingContext2D;
private parent: PageElement;
private random: Random = new Random();
private blobs: Array<HTMLElement> = [];
public constructor(
private readonly start: PageElement,
private readonly inBetween: Array<PageElement>,
private readonly end: PageElement
private readonly topOffsetElementCount: number,
private readonly bottomOffsetElementCount: number
) {
super(createElement(generate()));
this.canvas = this.htmlRoot as HTMLCanvasElement;
this.ctx = this.canvas.getContext('2d');
}
public handleOnLoadEvent(event: OnLoadEvent): OptionalEvent {
this.parent = event.parent;
requestAnimationFrame(this.draw.bind(this));
return super.handleOnLoadEvent(event);
}
public handleOnPageThemeChangedEvent(event: OnPageThemeChangedEvent): OptionalEvent {
Blob.changeTheme(event.isDark);
this.blobs.forEach(b => b.decideColor());
return super.handleOnPageThemeChangedEvent(event);
}
private createBlobs() {
const requiredBlobCount = Math.max(
PageBackground.minBlobCount,
(this.backgroundSize.x * this.backgroundSize.y) / PageBackground.blobSpacing ** 2
);
while (requiredBlobCount > this.blobs.length) {
this.blobs.push(new Blob());
for (let i = 0; i < window.innerWidth / 10; i++) {
const blob = document.createElement('div');
blob.classList.add('blob');
blob.style.width = '140px';
const z = this.random.inInterval(PageBackground.zMin, PageBackground.zMax);
blob.style.zIndex = (-z).toFixed(0);
blob.style.opacity = (
1 -
(z - PageBackground.zMin) / (PageBackground.zMax - PageBackground.zMin)
).toString();
blob.style.height = `${this.random.inInterval(360, 740)}px`;
this.blobs.push(blob);
this.htmlRoot.appendChild(blob);
}
}
private resizeCanvas() {
this.canvas.width = this.canvas.clientWidth;
this.canvas.height = this.canvas.clientHeight;
}
private windowHeight = 0;
private windowWidth = 0;
private contentHeight = 0;
private drawIfNecessary() {
const siblings = this.getSiblings();
const currentContentHeight = sum(siblings.map(getHeight));
private resizeBackground() {
const targetWidth = this.parent.htmlRoot.clientWidth;
if (
window.innerWidth !== this.windowWidth ||
window.innerHeight !== this.windowHeight ||
currentContentHeight !== this.contentHeight
) {
this.windowWidth = window.innerWidth;
this.windowHeight = window.innerHeight;
this.contentHeight = currentContentHeight;
const siblings: Array<HTMLElement> = this.getSiblings();
const targetHeight = sum(siblings.map(getHeight));
if (targetWidth === this.canvas.width && targetHeight === this.canvas.height) {
return;
}
const targetSize = new Vec2(targetWidth, targetHeight);
this.backgroundSize = targetSize;
this.blobs.forEach(blob => {
const variableOffset = (offset, q) =>
Math.max(
0,
offset -
((blob.z - PageBackground.zMin) /
(PageBackground.zMax - PageBackground.zMin)) *
offset *
q
);
const topOffset = variableOffset(getHeight(this.start.htmlRoot), 1);
const topLeft = this.convertFrom2Dto3D(new Vec2(0, topOffset), blob.z);
const bottomOffset = variableOffset(getHeight(this.end.htmlRoot), 0.2);
const bottomRight = this.convertFrom2Dto3D(
new Vec2(this.canvas.width, this.canvas.height - bottomOffset),
blob.z,
targetSize.y - this.canvas.height
this.randomizeBlobs(
sum(siblings.slice(0, this.topOffsetElementCount).map(getHeight)),
sum(siblings.slice(-this.bottomOffsetElementCount).map(getHeight))
);
}
blob.positionOffset = topLeft;
blob.positionScale = bottomRight.subtract(topLeft);
});
requestAnimationFrame(this.drawIfNecessary.bind(this));
}
private parent?: HTMLElement;
protected setParent(parent: PageElement) {
this.parent = parent.htmlRoot;
requestAnimationFrame(this.drawIfNecessary.bind(this));
super.setParent(parent);
}
private getSiblings(): Array<HTMLElement> {
return [this.start, ...this.inBetween, this.end].map(e => e.htmlRoot);
return Array.prototype.slice
.call(this.parent!.childNodes)
.filter((n: HTMLElement) => n !== this.htmlRoot);
}
private draw(timestamp: DOMHighResTimeStamp) {
this.resizeCanvas();
this.resizeBackground();
this.createBlobs();
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
const deltaTime = this.getDeltaTime(timestamp);
this.blobs.forEach(b => b.step(deltaTime));
this.scrollPosition = this.parent.htmlRoot.scrollTop;
this.blobs.sort((b1, b2) => b2.z - b1.z);
this.blobs.forEach(blob => {
const topLeft = this.convertFrom3Dto2D(blob.topLeft);
const bottomRight = this.convertFrom3Dto2D(
blob.topLeft.add(Vec3.from(blob.size, 0))
);
if (this.isInView(topLeft, bottomRight)) {
blob.draw(this.ctx, topLeft, bottomRight.subtract(topLeft));
}
private randomizeBlobs(topOffset: number, bottomOffset: number) {
this.random.seed = 50;
this.blobs.forEach(b => {
const z = -Number.parseInt(b.style.zIndex);
const [x, y] = this.randomXY(z, topOffset, bottomOffset);
b.style.transform = `translate3D(${x}px, ${y}px, ${-z}px) rotate(-20deg)`;
});
requestAnimationFrame(this.draw.bind(this));
}
private getDeltaTime(timestamp: DOMHighResTimeStamp): number {
const deltaTime = this.previousTimestamp ? timestamp - this.previousTimestamp : 0;
this.previousTimestamp = timestamp;
return Math.max(0, deltaTime);
}
private convertFrom3Dto2D(p: Vec3): Vec2 {
const m = PageBackground.perspective / (PageBackground.perspective + p.z);
return new Vec2(m * (p.z / 2 + p.x), m * (p.z / 2 + p.y - this.scrollPosition));
}
private convertFrom2Dto3D(p: Vec2, z: number, scrollPosition = 0): Vec2 {
const m = 1 + z / PageBackground.perspective;
return new Vec2(p.x * m - z / 2, p.y * m - z / 2 + scrollPosition);
}
private isInView(topLeft: Vec2, bottomRight: Vec2): boolean {
return (
((0 <= topLeft.x && topLeft.x <= this.canvas.width) ||
(0 <= bottomRight.x && bottomRight.x < this.canvas.width)) &&
((0 <= topLeft.y && topLeft.y <= this.canvas.height) ||
(0 <= bottomRight.y && bottomRight.y <= this.canvas.height))
private randomXY(z: number, topOffset: number, bottomOffset: number): [number, number] {
const farTop = -(
((this.windowHeight / 2 - topOffset) / PageBackground.perspective) *
(PageBackground.zMax + PageBackground.perspective) -
this.windowHeight / 2
);
const farBottom =
((this.windowHeight / 2 - bottomOffset) / PageBackground.perspective) *
(PageBackground.zMax + PageBackground.perspective) -
this.windowHeight / 2 +
this.contentHeight;
const endXSpan =
((this.windowWidth / PageBackground.perspective) *
(PageBackground.zMax + PageBackground.perspective)) /
2;
return [
this.random.inInterval(
mix(0, -(endXSpan - this.windowWidth / 2), z / PageBackground.zMax),
mix(
this.windowWidth,
this.windowWidth + endXSpan - this.windowWidth / 2,
z / PageBackground.zMax
)
),
this.random.inInterval(
mix(topOffset, farTop, z / PageBackground.zMax),
mix(this.contentHeight - bottomOffset, farBottom, z / PageBackground.zMax)
),
];
}
}

View file

@ -1,100 +0,0 @@
import { Vec2 } from './vec2';
import { Vec3 } from './vec3';
import { Random } from '../../helper/random';
import { Animation } from './animation';
import { PageBackground } from './background';
import { mix } from '../../helper/mix';
export class Blob {
private static readonly darkColors = [new Vec3(44, 71, 122)];
private static readonly lightColors = [
new Vec3(255, 249, 224),
new Vec3(255, 214, 214),
];
private static readonly creatorRandom = new Random(51);
private static colorPickerRandom = new Random(132);
private static isDarkThemed = false;
public static changeTheme(isDarkThemed: boolean) {
Blob.colorPickerRandom = new Random(132);
Blob.isDarkThemed = isDarkThemed;
}
public readonly z = Blob.creatorRandom.randomInInterval(
PageBackground.zMin,
PageBackground.zMax
);
private color: Animation<Vec3>;
private readonly positionQ = new Vec2(Blob.creatorRandom.next, Blob.creatorRandom.next);
private _positionScale = new Vec2(0, 0);
private _positionOffset = new Vec2(0, 0);
private opacity: number;
private readonly _size = new Vec2(140, Blob.creatorRandom.randomInInterval(260, 740));
public constructor() {
this.opacity =
1 - (this.z - PageBackground.zMin) / (PageBackground.zMax - PageBackground.zMin);
this.decideColor();
}
public decideColor() {
const target = Blob.colorPickerRandom.choose(
Blob.isDarkThemed ? Blob.darkColors : Blob.lightColors
);
this.color = new Animation<Vec3>(
this.color ? this.color.value : target,
target,
125,
(f, t, q) => {
return new Vec3(mix(f.x, t.x, q), mix(f.y, t.y, q), mix(f.z, t.z, q));
}
);
}
public step(deltaTime: number) {
this.color?.step(deltaTime);
}
public get topLeft(): Vec3 {
return Vec3.from(
this.positionQ.multiply(this._positionScale).add(this._positionOffset),
this.z
);
}
public get size(): Vec2 {
return this._size;
}
public set positionScale(value: Vec2) {
this._positionScale = value;
}
public set positionOffset(value: Vec2) {
this._positionOffset = value;
}
public draw(ctx: CanvasRenderingContext2D, position: Vec2, size: Vec2) {
ctx.save();
ctx.translate(position.x, position.y);
ctx.rotate((-20 / 180) * Math.PI);
ctx.beginPath();
ctx.arc(0, size.x / 2, size.x / 2, Math.PI, 0);
ctx.arc(0, size.y - size.x / 2, size.x / 2, 0, Math.PI);
ctx.closePath();
const { x, y, z } = this.color.value;
ctx.fillStyle = `rgba(${x}, ${y}, ${z}, ${this.opacity})`;
ctx.fill();
ctx.restore();
}
}

View file

@ -1,17 +0,0 @@
export class Vec2 {
public static readonly Zero = new Vec2(0, 0);
public constructor(public readonly x: number, public readonly y: number) {}
public add(other: Vec2): Vec2 {
return new Vec2(this.x + other.x, this.y + other.y);
}
public subtract(other: Vec2): Vec2 {
return new Vec2(this.x - other.x, this.y - other.y);
}
public multiply(other: Vec2): Vec2 {
return new Vec2(this.x * other.x, this.y * other.y);
}
}

View file

@ -1,23 +0,0 @@
import { Vec2 } from './vec2';
export class Vec3 {
public static readonly Zero = new Vec3(0, 0, 0);
public static from(vec2: Vec2, z: number): Vec3 {
return new Vec3(vec2.x, vec2.y, z);
}
public constructor(
public readonly x: number,
public readonly y: number,
public readonly z: number
) {}
public add(other: Vec3): Vec3 {
return new Vec3(this.x + other.x, this.y + other.y, this.z + other.z);
}
public multiply(other: Vec3): Vec3 {
return new Vec3(this.x * other.x, this.y * other.y, this.z * other.z);
}
}

View file

@ -1,13 +1,9 @@
import { PageElement } from '../page-element';
import { OnLoadEvent } from '../../events/concrete-events/on-load-event';
import { OnEventBroadcasterChangedEvent } from '../../events/concrete-events/on-event-broadcaster-changed-event';
export class Body extends PageElement {
constructor(root: HTMLElement, children: Array<PageElement>) {
super(root);
constructor(...children: Array<PageElement>) {
super(document.body, children);
children.forEach(c => this.attachElement(c));
this.broadcastEvent(new OnEventBroadcasterChangedEvent(this));
this.broadcastEvent(new OnLoadEvent(this));
this.setParent();
}
}

View file

@ -0,0 +1,6 @@
import './main.scss';
import { html } from '../../types/html';
export const generate = (): html => `
<main></main>
`;

21
src/page/main/main.scss Normal file
View file

@ -0,0 +1,21 @@
@use '../../style/mixins' as *;
main {
height: 100%;
overflow-x: hidden;
overflow-y: scroll;
perspective: 5px;
@media (hover: hover) {
&::-webkit-scrollbar-track,
&::-webkit-scrollbar {
background-color: transparent;
width: 12px;
}
&::-webkit-scrollbar-thumb {
background-color: var(--accent-color);
border-radius: var(--border-radius);
}
}
}

10
src/page/main/main.ts Normal file
View file

@ -0,0 +1,10 @@
import { PageElement } from '../page-element';
import { generate } from './main.html';
import { createElement } from '../../helper/create-element';
export class Main extends PageElement {
constructor(...children: Array<PageElement>) {
super(createElement(generate()), children);
children.forEach(c => this.attachElement(c));
}
}

View file

@ -1,46 +1,21 @@
import { EventHandler } from '../events/event-handler';
import { EventBroadcaster } from '../events/event-broadcaster';
import { OnEventBroadcasterChangedEvent } from '../events/concrete-events/on-event-broadcaster-changed-event';
import { OptionalEvent } from '../events/optional-event';
import { Event } from '../events/event';
import { OnLoadEvent } from '../events/concrete-events/on-load-event';
export abstract class PageElement extends EventHandler implements EventBroadcaster {
protected eventBroadcaster: EventBroadcaster;
export abstract class PageElement {
public constructor(
public readonly htmlRoot?: HTMLElement,
public readonly htmlRoot: HTMLElement,
protected children: Array<PageElement> = []
) {
super();
) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected setParent(parent?: PageElement): void {
this.children.forEach(c => c.setParent(this));
}
public broadcastEvent(event: Event) {
event = this.handle(event);
if (event) {
this.children.forEach(c => c.broadcastEvent(event));
}
}
public handleOnEventBroadcasterChangedEvent(
event: OnEventBroadcasterChangedEvent
): OptionalEvent {
this.eventBroadcaster = event.broadcaster;
return super.handleOnEventBroadcasterChangedEvent(event);
}
public handleOnLoadEvent(_: OnLoadEvent): OptionalEvent {
return super.handleOnLoadEvent(new OnLoadEvent(this));
}
protected query(query: string): HTMLElement | null {
return this.htmlRoot?.querySelector(query);
protected query(query: string): HTMLElement {
return this.htmlRoot.querySelector(query) as HTMLElement;
}
protected attachElementByReplacing(query: string, element: PageElement) {
const old = this.query(query);
old.parentElement.replaceChild(element.htmlRoot, old);
old.parentElement!.replaceChild(element.htmlRoot, old);
this.children.push(element);
}