Debian Codegraph @

html_renderer/src/lib/CanvasView.ts

raw symbols SCIP
1 import DevicePixelRatioObserver from "./DevicePixelRatioObserver"
2
3 export default abstract class CanvasView {
4 canvas: HTMLCanvasElement
5 _size_observer: ResizeObserver
6 _devicePixelRatioObserver: DevicePixelRatioObserver
7
8 constructor(readonly container: HTMLElement) {
9 if (getComputedStyle(container).position != "absolute") {
10 container.style.position = 'relative'
11 }
12
13 this.canvas = document.createElement('canvas')
14 this.canvas.style.position = 'absolute'
15 this.canvas.style.left = '0'
16 this.canvas.style.top = '0'
17 this.canvas.style.width = '100%'
18 this.canvas.style.height = '100%'
19 this.container.appendChild(this.canvas)
20
21 this.setCanvasSize = this.setCanvasSize.bind(this);
22
23 this._size_observer = new ResizeObserver(this.setCanvasSize)
24 this._size_observer.observe(container);
25
26 this._devicePixelRatioObserver = new DevicePixelRatioObserver(this.setCanvasSize)
27
28 // set the canvas size on the next redraw - avoids problems with window
29 // size changing during the first paint because of the scroll bar
30 window.requestAnimationFrame(() => {
31 this.setCanvasSize();
32 });
33 }
34
35 destroy() {
36 this._size_observer.disconnect()
37 this._devicePixelRatioObserver.destroy()
38 this.canvas.remove();
39 if (this.drawAnimationRequest !== null) {
40 window.cancelAnimationFrame(this.drawAnimationRequest);
41 this.drawAnimationRequest = null
42 }
43 }
44
45 drawAnimationRequest: any = null
46
47 setNeedsRedraw() {
48 if (this.drawAnimationRequest !== null) {
49 return
50 }
51
52 this.drawAnimationRequest = window.requestAnimationFrame(() => {
53 this.drawAnimationRequest = null;
54 this.canvasViewRedraw()
55 })
56 }
57
58 redrawIfNeeded() {
59 if (this.drawAnimationRequest !== null) {
60 window.cancelAnimationFrame(this.drawAnimationRequest);
61 this.drawAnimationRequest = null;
62 this.canvasViewRedraw()
63 }
64 }
65
66 canvasViewRedraw() {
67 const ctx = this.canvas.getContext('2d')
68 if (!ctx) return
69
70 ctx.resetTransform()
71 ctx.scale(window.devicePixelRatio, window.devicePixelRatio)
72
73 this.redraw(ctx, {
74 width: this.canvas.width / window.devicePixelRatio,
75 height: this.canvas.height / window.devicePixelRatio
76 });
77 }
78 abstract redraw(ctx: CanvasRenderingContext2D, extra: { width: number, height: number }): void
79
80 get width() { return this.canvas.width / window.devicePixelRatio }
81 get height() { return this.canvas.height / window.devicePixelRatio }
82
83 setCanvasSize() {
84 const ratio = window.devicePixelRatio
85 this.canvas.height = this.container.clientHeight * ratio;
86 this.canvas.width = this.container.clientWidth * ratio;
87 this.canvasViewRedraw()
88 }
89 }