Last active
December 5, 2022 23:25
-
-
Save kagklis/fc5d1365634cef7c170c172ff0f9e7e0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Component({ | |
// ... | |
}) | |
export class ChartComponent implements AfterViewInit { | |
private currentWorker: Worker; | |
private get size() { | |
return { | |
width: (3 * window.innerWidth) / 4, | |
height: (3 * window.innerHeight) / 4, | |
}; | |
} | |
// ... | |
private renderWithWorker(data: ChartData) { | |
const payload = { type: 'bar', data }; | |
if (!this.currentWorker) { | |
this.initWorker(); | |
this.firstDraw(payload); | |
} else { | |
this.redraw(payload); | |
} | |
} | |
private initWorker(): void { | |
this.currentWorker = new Worker( | |
new URL('./chart.worker', import.meta.url) | |
); | |
this.currentWorker.onmessage = () => { | |
this.isLoading = false; | |
}; | |
} | |
private firstDraw(chartData: ChartConfiguration): void { | |
const offscreen = this.createCanvas(); | |
this.currentWorker.postMessage({ | |
type: 'firstDraw', | |
canvas: offscreen, | |
...this.size, | |
chartData | |
}, [offscreen]); | |
} | |
private createCanvas() { | |
const currentCanvas = document.createElement('canvas'); | |
document.getElementById('chartCanvas').append(currentCanvas); | |
return (currentCanvas as any).transferControlToOffscreen(); | |
} | |
private redraw(chartData: ChartConfiguration): void { | |
this.currentWorker.postMessage({ | |
type: 'redraw', | |
...this.size, | |
chartData | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment