123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- function StarfieldGame() {
- var container = null;
- var canvas = null;
- var contextType = '2d';
- var contextAttributes = {};
- var context = null;
- var game = null;
- var starfields = [];
- var velocity = { x: -1, y: -1 };
- this.create = function (elementName, mouseBind) {
- game = this;
- container = document.getElementById(elementName);
- canvas = container.getElementsByTagName('canvas')[0];
- window.addEventListener('resize', game.handleResize);
- window.addEventListener('mousemove', game.handleMouseMove);
- window.requestAnimationFrame(game.handleRequestAnimationFrame);
- this.handleResize(null);
- };
- this.handleResize = function (event) {
- canvas.width = container.offsetWidth;
- canvas.height = container.offsetHeight;
- context = canvas.getContext(contextType, contextAttributes);
- context.translate(0.5, 0.5);
- game.init(canvas);
- }
- this.handleRequestAnimationFrame = function (event) {
- game.update(canvas);
- context.fillStyle = "#000000";
- context.fillRect(0, 0, canvas.width, canvas.height);
- game.draw(context);
- window.requestAnimationFrame(game.handleRequestAnimationFrame);
- }
- this.handleMouseMove = function (event) {
- //game.mouseMove(canvas, event.offsetX, event.offsetY);
- game.mouseMove(canvas, event.clientX, event.clientY);
- let canvasBounds = canvas.getBoundingClientRect();
- if (event.clientX < canvasBounds.x ||
- event.clientX > canvasBounds.x + canvasBounds.width ||
- event.clientY < canvasBounds.y ||
- event.clientY > canvasBounds.y + canvasBounds.height) {
- game.mouseMove(canvas, canvas.width / 2, event.clientY = canvas.height / 2);
- return;
- }
- game.mouseMove(canvas, event.clientX, event.clientY);
- }
- this.init = function (canvas) {
- starfields = [];
- for (var i = 0; i < 3; i++) {
- starfields.push(new Starfield());
- }
- for (var i = 0, starfield = starfields[0]; starfield = starfields[i]; i++) {
- starfield.init(canvas, i + 1, velocity);
- }
- };
- this.update = function (canvas) {
- for (var i = 0, starfield = starfields[0]; starfield = starfields[i]; i++) {
- starfield.update(canvas);
- }
- };
- this.draw = function (context) {
- for (var i = 0, starfield = starfields[0]; starfield = starfields[i]; i++) {
- starfield.draw(context);
- }
- };
- this.mouseMove = function (canvas, x, y) {
- for (var i = 0, starfield = starfields[0]; starfield = starfields[i]; i++) {
- starfield.mouseMove(canvas, x, y);
- }
- };
- }
|