This demo provides a very simple implementation for handling layers within one screen.
- Press T - Toggle the various layers visiblity.
- Or click on the screen to toggle layer visibility.
This demo provides a very simple implementation for handling layers within one screen.
To create a named layer, invoke addLayer and it'll return a reference to the newly created named layer. The reference can be used to set layer specific properties such as viewports, border & background colors, etc.
constructor(options = {}) { super(options); this.primaryScreen.backgroundColor = '#87CEEB'; //Create the layers and retrieve a reference to updated properties. const layer0 = this.primaryScreen.addLayer('layer0'); const layer1 = this.primaryScreen.addLayer('layer1'); ... }
Using the method getLayer will retrieved the named layer from the screen. Drawing to a layer is the same as drawing to the screen. Once all drawing is completed the method draw can be called on the screen to render all layers to the screen.
/** * An onFrame event that is triggered when a single frame is being rendered to the canvas. * @param {number} elapsedTimeInMilliseconds since the last frame. */ onFrame(elapsedTimeInMilliseconds) { //Always begin painting before drawing anything to clear the previous etching on the canvas, as well as set the viewport and fill color. this.primaryScreen.beginPainting(); //----------------------- //Add drawing logic here. //----------------------- //Draw to layer 0 { const layer = this.primaryScreen.getLayer('layer0'); const x = layer.viewPort.center.x; const y = layer.viewPort.center.y; layer.beginPainting(); layer.drawText(`Layer 0`, x, y, { font: '48px serif', color: 'yellow', textOffset: 'center', verticalTextOffset: 'center', shadow: true }); layer.endPainting(); } //Draw to layer 1 { const layer = this.primaryScreen.getLayer('layer1'); const x = layer.viewPort.center.x; const y = layer.viewPort.center.y; layer.beginPainting(); layer.drawText(`Layer 1`, x, y + 48, { font: '48px serif', color: 'red', textOffset: 'center', verticalTextOffset: 'center', shadow: true }); layer.endPainting(); } //Draw all the layers onto the screen. this.primaryScreen.draw(); //End painting to clean up and restore the canvas to a state before transformations were applied. this.primaryScreen.endPainting(); }
Layer visiblity can be toggled by using the visible property.
toggleLayers() { //Make all layers visible. this.primaryScreen.getLayer('layer0').visible = this.primaryScreen.getLayer('layer1').visible = true; //Toggle the layer. const layerToToggle = this.primaryScreen.getLayer(`layer${this._layerToggleIndex}`); if (layerToToggle) { layerToToggle.visible = false; } this._layerToggleIndex = (this._layerToggleIndex + 1) % 3; }