|
| 1 | +import { parse } from 'ass-compiler' |
| 2 | +import { ASSOptions } from './types' |
| 3 | +import { newCanvas } from './utils' |
| 4 | + |
| 5 | +export default class ASS { |
| 6 | + assText: string |
| 7 | + video: HTMLVideoElement | string |
| 8 | + videoElement: HTMLVideoElement | null = null |
| 9 | + canvas: HTMLCanvasElement| null = null |
| 10 | + constructor( |
| 11 | + options: ASSOptions |
| 12 | + ) { |
| 13 | + this.assText = options.assText |
| 14 | + this.video = options.video |
| 15 | + } |
| 16 | + |
| 17 | + init() { |
| 18 | + if (typeof this.video == 'string') { |
| 19 | + this.videoElement = document.querySelector(this.video) |
| 20 | + if (this.videoElement === null) { |
| 21 | + throw new Error("Unable to find the video element") |
| 22 | + } |
| 23 | + } else { |
| 24 | + this.videoElement = this.video |
| 25 | + } |
| 26 | + console.log(this.videoElement) |
| 27 | + this.setCanvasSize() |
| 28 | + |
| 29 | + this.videoElement?.addEventListener('loadedmetadata', () => { |
| 30 | + this.setCanvasSize() |
| 31 | + }) |
| 32 | + |
| 33 | + window.addEventListener('resize', () => { |
| 34 | + this.setCanvasSize(); |
| 35 | + }); |
| 36 | + } |
| 37 | + |
| 38 | + |
| 39 | + setCanvasSize() { |
| 40 | + console.log("set Canva size") |
| 41 | + const { videoWidth, videoHeight, offsetTop, offsetLeft } = this.videoElement as HTMLVideoElement |
| 42 | + const aspectRatio = videoWidth / videoHeight; |
| 43 | + |
| 44 | + const maxWidth = this.videoElement?.clientWidth || 0; |
| 45 | + const maxHeight = this.videoElement?.clientHeight || 0; |
| 46 | + |
| 47 | + let width = maxWidth; |
| 48 | + let height = maxHeight; |
| 49 | + let x = offsetLeft; |
| 50 | + let y = offsetTop; |
| 51 | + |
| 52 | + if (maxHeight * aspectRatio > maxWidth) { |
| 53 | + width = maxWidth; |
| 54 | + height = width / aspectRatio; |
| 55 | + y += (maxHeight - height) / 2; |
| 56 | + } else { |
| 57 | + height = maxHeight; |
| 58 | + width = height * aspectRatio; |
| 59 | + x += (maxWidth - width) / 2; |
| 60 | + } |
| 61 | + |
| 62 | + if (this.canvas === null) { |
| 63 | + this.canvas = newCanvas(y, x, width, height, this.videoElement as HTMLVideoElement) |
| 64 | + } else { |
| 65 | + this.canvas.style.position = 'absolute'; |
| 66 | + this.canvas.style.top = y + 'px'; |
| 67 | + this.canvas.style.left = x + 'px'; |
| 68 | + this.canvas.style.width = width + 'px'; |
| 69 | + this.canvas.style.height = height + 'px'; |
| 70 | + this.canvas.width = width; |
| 71 | + this.canvas.height = height; |
| 72 | + } |
| 73 | + |
| 74 | + } |
| 75 | +} |
0 commit comments