Optional
canvas: CanvasSelectorThe canvas element, selector, or ChildCanvasBG.
Optional
config: Record<string, unknown>Optional configuration options.
// Create a CanvasBG instance with a canvas element
const canvasBG = new CanvasBG(document.getElementById('myCanvas'));
// Create a CanvasBG instance with a canvas selector
const canvasBG = new CanvasBG('#myCanvas');
// Create a CanvasBG instance with another CanvasBG instance
const mainCanvas = new CanvasBG();
const childCanvasBG = new CanvasBG(mainCanvas);
If you are extending the CanvasBG class with a subclass, make sure to call
the superclass constructor using super()
within the constructor of the subclass.
Readonly
defaultGets the default alias for the CanvasBG class.
Gets the layers associated with the current CanvasBG instance. The layers are stored as key-value pairs, where the key is the layer name and the value is the associated CanvasBG instance. the __main key is reserved for the main CanvasBG instance. zIndex is used to sort the layers.
const bg = new CanvasBG(".bg-canvas")
.use(new StarField(null, { speed: { x: 0, y: 0, z: 0.001 }, points: 150 }))
.use(new MouseTracker(), { as: "mousetracker", zIndex:100}) // associate with a key
.use(new Constellation()); // associate without a key (default key is the class name)
console.log(bg.layers.__main === bg); // true
layers is always points same address on all siblings
const mainCanvas = new CanvasBG();
const starField = new StarField(mainCanvas);
const mouseTracker = new MouseTracker(mainCanvas);
mainCanvas
.use(starField, { as: "starfield" })
.use(mouseTracker, { as: "mousetracker" });
console.log(mainCanvas.layers === starField.layers); // true
@returns The layers associated with the current CanvasBG instance.
@remarks Do not modify this property directly; use the `use` method to associate layers.
Initiates the animation loop for the canvas. This method clears the canvas, calls the draw method to draw one frame, and schedules the next frame using requestAnimationFrame(). You can override the draw method to customize drawing behavior. Make sure to call this method after binding the canvas context.
const bg = new CanvasBG(".bg-canvas")
.use(new StarField(null, { speed: { x: 0, y: 0, z: 0.001 }, points: 150 }))
.use(new MouseTracker())
.use(new Constellation());
bg.animate();
Don't override this method; it is used internally to bind the context.
Associates the current CanvasBG instance with another CanvasBG instance.
This method binds the current instance with the provided canvasbg
instance,
allowing the current instance to inherit properties and functionality
from the provided instance.
(see animate() method for a complete example)
The CanvasBG instance to be associated with.
Optional
config: Partial<LayerConfig>The current CanvasBG instance after association.
Don't override this method; it is used internally to bind the context.
A class to track the mouse position on the canvas.
Example