@@ -10,6 +10,7 @@ import { FireworksOptions, IBoundaries, Sizes } from './types.js'
1010declare const version : string
1111
1212export class Fireworks {
13+ private target : Element | HTMLCanvasElement
1314 private container : Element
1415 private canvas : HTMLCanvasElement
1516 private ctx : CanvasRenderingContext2D
@@ -30,19 +31,11 @@ export class Fireworks {
3031 container : Element | HTMLCanvasElement ,
3132 options : FireworksOptions = { }
3233 ) {
34+ this . target = container
3335 this . container = container
3436
35- if ( container instanceof HTMLCanvasElement ) {
36- this . canvas = container
37- } else {
38- this . canvas = document . createElement ( 'canvas' )
39- this . container . appendChild ( this . canvas )
40- }
41-
42- this . ctx = this . canvas . getContext ( '2d' ) !
43-
37+ this . createCanvas ( this . target )
4438 this . updateOptions ( options )
45- this . updateSize ( )
4639
4740 this . sound = new Sound ( )
4841 this . resize = new Resize ( this )
@@ -60,20 +53,28 @@ export class Fireworks {
6053 start ( ) : void {
6154 if ( this . running ) return
6255
56+ if ( ! this . canvas . isConnected ) {
57+ this . createCanvas ( this . target )
58+ }
59+
6360 this . running = true
6461 this . resize . subscribe ( )
6562 this . mouse . subscribe ( )
6663 this . clear ( )
6764 this . render ( )
6865 }
6966
70- stop ( ) : void {
67+ stop ( dispose = false ) : void {
7168 if ( ! this . running ) return
7269
7370 this . running = false
7471 this . resize . unsubscribe ( )
7572 this . mouse . unsubscribe ( )
7673 this . clear ( )
74+
75+ if ( dispose ) {
76+ this . canvas . remove ( )
77+ }
7778 }
7879
7980 pause ( ) : void {
@@ -96,12 +97,8 @@ export class Fireworks {
9697 }
9798
9899 updateSize ( {
99- width = this . container instanceof HTMLCanvasElement
100- ? this . canvas . width
101- : this . container . clientWidth ,
102- height = this . container instanceof HTMLCanvasElement
103- ? this . canvas . height
104- : this . container . clientHeight
100+ width = this . container . clientWidth ,
101+ height = this . container . clientHeight
105102 } : Partial < Sizes > = { } ) : void {
106103 this . width = width
107104 this . height = height
@@ -120,6 +117,22 @@ export class Fireworks {
120117 this . updateOptions ( { boundaries } )
121118 }
122119
120+ private createCanvas ( el : Element | HTMLCanvasElement ) : void {
121+ if ( el instanceof HTMLCanvasElement ) {
122+ if ( ! el . isConnected ) {
123+ document . body . append ( el )
124+ }
125+
126+ this . canvas = el
127+ } else {
128+ this . canvas = document . createElement ( 'canvas' )
129+ this . container . append ( this . canvas )
130+ }
131+
132+ this . ctx = this . canvas . getContext ( '2d' ) !
133+ this . updateSize ( )
134+ }
135+
123136 private render ( timestamp = this . timestamp ) : void {
124137 if ( ! this . ctx || ! this . running ) return
125138
0 commit comments