Path: blob/main/public/games/files/garbage-collector/js/effects/background.js
1036 views
/*globals define*/1define([2'object2d',3'utils'4], function( Object2D, Utils ) {5'use strict';67var defaults = {8count: 100,9parallax: 0.25,1011hueSpread: 50,12saturationSpread: 15,13lightnessSpread: 2514};1516function Background( width, height, options ) {17Object2D.call( this, 0, 0 );1819Utils.defaults( this, options, defaults );2021this.canvas = document.createElement( 'canvas' );22this.ctx = this.canvas.getContext( '2d' );2324this.width = width || 0;25this.height = height || 0;2627this.game = null;28this.camera = null;29}3031Background.prototype = new Object2D();32Background.prototype.constructor = Background;3334Background.prototype.prerender = function() {35var hsl = this.fill.hslObject();3637var hue = hsl.hue,38saturation = hsl.saturation,39lightness = hsl.lightness;4041var width = this.width,42height = this.height;4344var rects = [];45var rectCount = this.count;4647var rectHue, rectSaturation, rectLightness;48while ( rectCount-- ) {49rectHue = this.hueSpread ? Utils.intSpread( hue, this.hueSpread ) : hue;50rectSaturation = this.saturationSpread ? Utils.intSpread( saturation, this.saturationSpread ) : saturation;51rectLightness = this.lightnessSpread ? Utils.intSpread( lightness, this.lightnessSpread ): lightness;5253rects.push({54x: Math.random() * width,55y: Math.random() * height,56width: Utils.randomFloat( 0.05, 0.3 ) * width,57height: Utils.randomFloat( 0.05, 0.3 ) * height,58hue: rectHue,59saturation: rectSaturation + '%',60lightness: rectLightness + '%'61});62}6364var ctx = this.ctx;65ctx.fillStyle = this.fill.rgba();66ctx.fillRect( 0, 0, width, height );6768rects.forEach(function( rect ) {69ctx.save();70ctx.translate( rect.x, rect.y );7172ctx.beginPath();73ctx.rect( -0.5 * rect.width, -0.5 * rect.height, rect.width, rect.height );74ctx.fillStyle = 'hsla(' +75rect.hue + ', ' +76rect.saturation + ', ' +77rect.lightness + ', ' +78Math.random() +79')';8081ctx.fill();8283ctx.restore();84});85};8687Background.prototype.draw = function( ctx ) {88if ( !this.game || !this.camera ) {89return;90}9192ctx.save();93ctx.translate( this.camera.x * this.parallax, this.camera.y * this.parallax );94ctx.scale( this.parallax, this.parallax );9596ctx.drawImage( this.canvas, -0.5 * this.width, -0.5 * this.height );9798ctx.restore();99};100101Object.defineProperty( Background.prototype, 'width', {102get: function() {103return this.canvas.width;104},105106set: function( width ) {107this.canvas.width = width || 0;108}109});110111Object.defineProperty( Background.prototype, 'height', {112get: function() {113return this.canvas.height;114},115116set: function( height ) {117this.canvas.height = height || 0;118}119});120121return Background;122});123124125