Performance jQuery Ajax load game sources display as modal - javascript

I have a base website system which is using ajax load content without refreshing pages. I have a game page that load many html5 game links via ajax json and when I click on any games it will load the game source files which display as pop up. I am wonder while I'm playing then if I click the close button for stopping the game and then I remove the element of the source files game. Will it free up the memory? As I have noticed, it seems to getting slow the broswer. Anyone has experienced with that, please share with me.
Note: I need some suggestions in order to remove the elements and free up the memory.
eg:
<div id="pop-up">
<a id="close" href="#">Close Button</a>
<div id="inner-pop-up">
<script src="game sources" type="text/javascript"></script>
<script src="game sources" type="text/javascript"></script>
<script src="game sources" type="text/javascript"></script>
<div id="game">
<canvas></canvas>
</div>
</div>
</div>
$('#pop-up').modal('view', {
speed: 750,
close: '.close-favourite',
easing: 'easeOutBounce',
animation: 'top',
position: 'center',
overlayClose: true
});
$('#close').on('click', function() {
$('#inner-pop-up').children().remove();
});

The only real way to free up any resources used by script functions is to add a JavaScript file that basically calls delete window.myFunction for every possible object and function (functions are objects really) your specified script files may define. To me, for obvious reasons, this is a really bad idea.
Note that these objects would be script (window) objects so you cannot use .remove() to remove those.
I would also note that your should use $('#inner-pop-up').empty(); rather than your $('#inner-pop-up').children().remove(); since that would remove the text of the element if any, as well and specifically removes the data and event handlers from those elements prior to removal from the DOM.
You might have some very specific functions and objects from your scripts that you might want to remove here but only the contents of your scripts would tell that. If you create global window objects that gets really messy fast.
Note it is REALLY hard to determine what a script file creates and then remove it.
To prove a point open up your favorite browser console and execute $("script").remove(). stuff in that script still runs.

Eg: This is my game file which contained the object like that
FootballChallenge.Game = function (game) {
FootballChallenge._scoreText = null;
FootballChallenge._score = 0;
FootballChallenge.kickBoard;
this._preventClick = true;
FootballChallenge.kaboomGroup;
FootballChallenge.ball;
FootballChallenge.shoe;
FootballChallenge.self;
};
FootballChallenge.Game.prototype = {
create: function () {
FootballChallenge.self = this.game;
this.game.physics.startSystem(Phaser.Physics.ARCADE);
this.game.physics.arcade.checkCollision.up = false;
this.bg = this.game.add.image(this.game.world.centerX, this.game.world.centerY, 'field');
this.bg.anchor.setTo(0.5);
FootballChallenge.kickBoard = this.game.add.sprite(10, 20, 'kickBoard');
FootballChallenge._scoreText = this.game.add.bitmapText(0, FootballChallenge.kickBoard.height/2 + 20, 'white-font', ''+FootballChallenge._score+'', 32);
FootballChallenge._scoreText.align = 'center';
FootballChallenge._scoreText.x = (FootballChallenge.kickBoard.width-FootballChallenge._scoreText.width + 20)/2;
FootballChallenge.ball = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY - 100, 'ball');
this.game.physics.arcade.enable(FootballChallenge.ball);
FootballChallenge.ball.anchor.setTo(0.5);
FootballChallenge.ball.scale.setTo(0.5);
FootballChallenge.ball.body.collideWorldBounds = true;
FootballChallenge.ball.body.gravity.y = 0;
FootballChallenge.ball.body.bounce.setTo(1);
FootballChallenge.shoe = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY, 'shoe');
this.game.physics.arcade.enable(FootballChallenge.shoe);
FootballChallenge.shoe.anchor.setTo(0.5);
FootballChallenge.shoe.scale.setTo(0.5);
FootballChallenge.shoe.body.setSize(130,50,0,20);
FootballChallenge.shoe.body.collideWorldBounds = true;
FootballChallenge.kaboomGroup = this.game.add.group();
FootballChallenge.kaboomGroup.createMultiple(10, 'kaboom');
FootballChallenge.kaboomGroup.forEach(this.explosion, this);
this.play();
},
explosion: function(kick) {
kick.anchor.x = 0.7;
kick.anchor.y = 0.5;
kick.animations.add('kaboom');
},
play: function() {
this.bitmask = this.game.make.bitmapData(this.game.width, this.game.height);
this.bitmask.fill(50,50,50);
this.mask = this.game.add.sprite(0, 0, this.bitmask);
this.mask.tint = 0x000000;
this.mask.alpha = 0.6;
this.game.paused = true;
var pausedText = this.game.add.bitmapText(this.game.world.centerX, this.game.world.centerY - 200, 'white-font', 'click anywhere to begin!', 32);
pausedText.align = 'center';
pausedText.tint = 0xff0e25;
pausedText.anchor.setTo(0.5);
this.game.input.onDown.add(function(){
pausedText.destroy();
this.game.paused = false;
this.mask.alpha = 0;
FootballChallenge.ball.body.gravity.y = 1500;
this.game.canvas.style.cursor = "none";
}, this);
},
countScore: function(ball, shoe) {
ball.body.velocity.y = -1000;
ball.body.gravity.x = FootballChallenge.self.rnd.integerInRange(-80, 80);
FootballChallenge._scoreText.setText(FootballChallenge._score +=1);
FootballChallenge._scoreText.x = (FootballChallenge.kickBoard.width-FootballChallenge._scoreText.width + 20)/2;
var boom = FootballChallenge.kaboomGroup.getFirstExists(false);
boom.reset(shoe.x, shoe.y);
boom.play('kaboom', 40, false, true);
},
lose: function() {
this.game.state.start('EndGame');
},
update: function() {
if(FootballChallenge.ball.y >= this.game.height - 100) {
FootballChallenge.ball.body.gravity = false;
this.game.time.events.add(Phaser.Timer.SECOND * 0.2, this.lose, this);
}
this.game.physics.arcade.collide(FootballChallenge.ball, FootballChallenge.shoe, this.countScore);
this.game.physics.arcade.moveToPointer(FootballChallenge.shoe, 30, this.game.input.activePointer, 50);
}
};

Related

Intercept calls to HTML5 canvas element

I have a WEB application, that renders it's entire User Interface in an HTML5 canvas.
Note that I can't change the current application.
Currently, this application is being tested using Selenium.
This is done by simulating a click event at a given location in the browser window.
After the click has been executed, a sleep of 2 seconds is being performed to ensure that the entire UI is ready before moving to the next step.
Due to all the 'wait' statements, testing the application is very slow.
Therefore, I thought it was an idea to intercept all calls to the HTML5 canvas.
That way I can rely on the triggered events to know if the UI is ready to move to the next step.
Assume that I have the following code in my application that renders the canvas.
var canvas = document.getElementById("canvasElement");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(10, 10, 100, 100);
Is there a way to intercept the 'fillRect' event?
I tought something along the lines:
var canvasProxy = document.getElementById("canvasElement");
canvasProxy.addEventListener("getContext", function(event) {
console.log("Hello");
});
var canvas = document.getElementById("canvasElement");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(10, 10, 100, 100);
Unforuntately this is not working.
I've created a JSFiddle to play with the example.
https://jsfiddle.net/5cknym74/4/
Amy toughts?
I played a bit around with the JS API and it seems that the following might be working:
// SECTION: Store a reference to all the HTML5 'canvas' element methods.
HTMLCanvasElement.prototype._captureStream = HTMLCanvasElement.prototype.captureStream;
HTMLCanvasElement.prototype._getContext = HTMLCanvasElement.prototype.getContext;
HTMLCanvasElement.prototype._toDataURL = HTMLCanvasElement.prototype.toDataURL;
HTMLCanvasElement.prototype._toBlob = HTMLCanvasElement.prototype.toBlob;
HTMLCanvasElement.prototype._transferControlToOffscreen = HTMLCanvasElement.prototype.transferControlToOffscreen;
HTMLCanvasElement.prototype._mozGetAsFile = HTMLCanvasElement.prototype.mozGetAsFile;
// SECTION: Patch the HTML5 'canvas' element methods.
HTMLCanvasElement.prototype.captureStream = function(frameRate) {
console.log('INTERCEPTING: HTMLCanvasElement.prototype.captureStream');
return this._captureStream(frameRate);
}
HTMLCanvasElement.prototype.getContext = function(contextType, contextAttributes) {
console.log('INTERCEPTING: HTMLCanvasElement.prototype.getContext');
console.log('PROPERTIES:');
console.log(' contextType: ' + contextType);
return this._getContext(contextType, contextAttributes);
}
HTMLCanvasElement.prototype.toDataURL = function(type, encoderOptions) {
console.log('INTERCEPTING: HTMLCanvasElement.prototype.toDataURL');
return this._toDataURL(type, encoderOptions);
}
HTMLCanvasElement.prototype.toBlob = function(callback, mimeType, qualityArgument) {
console.log('INTERCEPTING: HTMLCanvasElement.prototype.toBlob');
return this._toBlob(callback, mimeType, qualityArgument);
}
HTMLCanvasElement.prototype.transferControlToOffscreen = function() {
console.log('INTERCEPTING: HTMLCanvasElement.prototype.transferControlToOffscreen');
return this._transferControlToOffscreen();
}
HTMLCanvasElement.prototype.mozGetAsFile = function(name, type) {
console.log('INTERCEPTING: HTMLCanvasElement.prototype.mozGetAsFile');
return this._mozGetAsFile(name, type);
}
Now that I can intercept the calls, I can find out which calls are responsible that draw a button and react accordingly.

why phaser game lagging in mobile devices

I am creating my first game using Phaser and it is running fine in desktop.
But it is lagging on android phones.
can anyone tell me what could be the reasons?
game is very small
smaller than 2mb.
Images used in game is also very tiny pngs.
is there anyway to find out any leaks in my code.
my main js file.
var buttetSpwanSpeed;
var bulletSpeed;
var enemySpwanSpeed;
var enemySpeed;
var golis;
var enemies;
var enemyLoop;
var scoreText;
var powers;
var bulletSize;
setStart();
//game phaser
var game=new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.CANVAS,"gamearea");
var BootState={
//loding accets
preload: function(){
this.load.image('LodingScreen', 'assets/desimulga.png');
this.load.image('background', 'assets/blue.png');
},
create: function(){
game.state.start("LoadingState");
},
};
var LoadingState={
//loding acc
preload: function(){
bg=this.game.add.tileSprite(0,0,600,300,'background');
bg.height = game.height;
bg.width = game.width;
LodingScreen=this.game.add.sprite(this.game.world.centerX,this.game.world.centerY,'LodingScreen');
LodingScreen.anchor.setTo(0.5);
LodingScreen.scale.setTo(0.5,0.5);
this.load.image('spaceship', 'assets/player.png');
this.load.image('goli', 'assets/bullet.png');
//load ememies
this.load.image('enemy1', 'assets/enemies/enemy1.png');
this.load.image('enemy2', 'assets/enemies/enemy2.png');
this.load.image('enemy3', 'assets/enemies/enemy3.png');
this.load.image('enemy4', 'assets/enemies/enemy4.png');
this.load.image('enemy5', 'assets/enemies/enemy5.png');
this.load.spritesheet('power1', 'assets/power/bulletUp.png',34,33,4);
this.load.image('restart', 'assets/restart.png');
this.load.spritesheet('blast', 'assets/explosion.png',400,400,8);
game.load.audio('fire', 'assets/music/bullet.mp3');
game.load.audio('killed', 'assets/music/killed.mp3');
//game.load.audio('bg_music', 'assets/music/background.mp3');
game.load.audio('death_music', 'assets/music/death.mp3');
game.load.audio('start_music', 'assets/music/start.mp3');
},
create: function(){
game.time.events.add(Phaser.Timer.SECOND * 2, function(){
bg.kill();
LodingScreen.kill();
game.state.start("PreGameState");
},this);
},
};
var PreGameState={
//loding accets
create: function(){
game.scale.refresh();
bg=this.game.add.tileSprite(0,0,600,300,'background');
bg.height = game.height;
bg.width = game.width;
Startb=this.game.add.text(this.game.world.centerX,this.game.world.centerY, 'TAP TO START' , { fontSize: '32px', fill: 'yellow' });
Startb.anchor.setTo(0.5);
Startb.scale.setTo(0.5,0.5);
ship=this.game.add.sprite(this.game.world.centerX,this.game.world.height*0.4,'spaceship');
ship.scale.setTo(0.4);
ship.anchor.setTo(0.5);
game.physics.arcade.enable(ship);
bg.inputEnabled=true;
start_music = game.add.audio('start_music');
start_music.allowMultiple = true;
start_music.addMarker('start_music', 0, 30);
bg.events.onInputDown.add(function(){
bg.inputEnabled=false;
Startb.kill();
start_music.play("start_music");
// game.physics.arcade.moveToXY(ship, this.game.world.centerX, this.game.world.height*0.8, 300, 3000);
// game.add.tween(ship).to( { y: game.world.height*0.8 }, 3000, Phaser.Easing.Sinusoidal.InOut, true);
var tween = game.add.tween(ship).to({
x: [this.game.world.centerX, this.game.world.width*0, this.game.world.width, this.game.world.centerX],
y: [this.game.world.height*0.4, this.game.world.height*0.5, this.game.world.height*0.6, this.game.world.height*0.8],
}, 2000,Phaser.Easing.Quadratic.Out, true).interpolation(function(v, k){
return Phaser.Math.bezierInterpolation(v, k);
});
game.time.events.add(Phaser.Timer.SECOND * 2, function() {
bg.kill();
ship.kill();
game.state.start("GameState");
} ,this);
}, this);
},
};
var GameState={
//loding accets
preload: function(){
},
create: function(){
//background
this.background=this.game.add.tileSprite(0,0,600,300,'background');
this.background.height = game.height;
this.background.width = game.width;
this.background.inputEnabled=true;
this.background.input.enableDrag(true);
this.background.input.startDrag = function(pointer) {
pointer.shipStart = new Phaser.Point(GameState.ship.x, GameState.ship.y);
Phaser.InputHandler.prototype.startDrag.call(this, pointer);
};
this.background.input.updateDrag = function(pointer) {
GameState.ship.x = pointer.shipStart.x - pointer.positionDown.x + pointer.x;
GameState.ship.y = pointer.shipStart.y - pointer.positionDown.y + pointer.y;
GameState.background.x=0;
GameState.background.y=0;
};
//ship
this.ship=this.game.add.sprite(this.game.world.centerX,this.game.world.height*0.8,'spaceship');
this.ship.scale.setTo(0.4);
this.ship.anchor.setTo(0.5);
game.physics.arcade.enable(this.ship);
// this.ship.inputEnabled=true;
// this.ship.input.enableDrag(true);
//score
this.scoreText = this.game.add.text(16, 16, 'Kills: 0', { fontSize: '32px', fill: '#fff' });
//background Music
// music = game.add.audio('bg_music');
//music.play('', 0, 1, true);
//bullet sound
bullet_sound = game.add.audio('fire');
bullet_sound.allowMultiple = true;
bullet_sound.volume=0.5;
bullet_sound.addMarker('fire', 0, 0.5);
//Killed sound
killed_sound = game.add.audio('killed');
killed_sound.allowMultiple = true;
killed_sound.addMarker('killed', 0, 0.5);
//death music
death_music = game.add.audio('death_music');
death_music.allowMultiple = true;
death_music.addMarker('death_music', 0, 10);
//groups of bullets and enemies
golis=game.add.group();
enemies=game.add.group();
powers=game.add.group();
//fire bullet loop
fireLoop=game.time.events.loop(Phaser.Timer.SECOND*1/buttetSpwanSpeed, fireBullet, this);
//this.game.input.onTap.add(fireBullet, this);
//create ememy loop
enemyLoop=game.time.events.loop(Phaser.Timer.SECOND*1/enemySpwanSpeed, createEnemy, this);
//change ememy speed and enemy spwan speed loop
enemySpeedLoop=game.time.events.loop(Phaser.Timer.SECOND*1.5, changeEnemySpeed, this);
//give powerup
powerUp=game.time.events.loop(Phaser.Timer.SECOND*20, powerFun, this);
},
update: function(){
//scrolling background
this.background.tilePosition.y+=2;
//keybord control
if (game.input.keyboard.isDown(Phaser.Keyboard.UP))
{
this.ship.y-=2;
}
if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN))
{
this.ship.y+=2;
}
if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT))
{
this.ship.x+=2;
}
if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT))
{
this.ship.x-=2;
}
//dont go out
if(this.ship.y<0+this.ship.height/2)
{
this.ship.y=0+this.ship.height/2;
}
if(this.ship.y>this.game.world.height-this.ship.height/2)
{
this.ship.y=this.game.world.height-this.ship.height/2;
}
if(this.ship.x<0+this.ship.width/2)
{
this.ship.x=0+this.ship.width/2;
}
if(this.ship.x>this.game.world.width-this.ship.width/2)
{
this.ship.x=this.game.world.width-this.ship.width/2;
}
//check for collisions
game.physics.arcade.overlap(golis,enemies,b_e_collide,null,this);
game.physics.arcade.overlap(this.ship,enemies,s_e_collide,null,this);
game.physics.arcade.overlap(this.ship,powers,s_power1_collide,null,this);
},
};
//setting start game conditions
function setStart(){
buttetSpwanSpeed=2;
bulletSpeed=2000;
enemySpwanSpeed=1;
enemySpeed=300;
score=0;
bulletSize=1.2
}
//fire bullet function
function fireBullet(){
goli=this.game.add.sprite(this.ship.x,this.ship.y-this.ship.height/2,'goli');
goli.anchor.setTo(0.5);
goli.scale.setTo(bulletSize,1);
goli.checkWorldBounds = true;
goli.outOfBoundsKill = true;
//adding to group
golis.add(goli);
game.world.moveDown(goli);
game.physics.arcade.enable(goli);
goli.body.collisonWorldBounds=true;
goli.body.velocity.y=-bulletSpeed;
bullet_sound.play("fire");
}
//create enemy function
function createEnemy(){
enemyNo=game.rnd.integerInRange(1, 5);
x1=game.rnd.integerInRange(0,this.game.world.width);
x2=game.rnd.integerInRange(0,this.game.world.width);
enemy=this.game.add.sprite(x1,10,'enemy'+enemyNo);
enemy.anchor.setTo(0.5);
enemy.scale.setTo(0.4);
enemy.checkWorldBounds = true;
enemies.add(enemy);
enemy.outOfBoundsKill = true;
game.physics.arcade.enable(enemy);
enemy.body.collisonWorldBounds=true;
enemy.angle=90;
enemy.no=enemyNo;
//moving enemy
angleRedian=game.physics.arcade.moveToXY(enemy, x2, this.game.world.height+enemy.height, enemySpeed,0);
angleDegree=angleRedian*57.2958;
enemy.angle=90+angleDegree;
}
//runs when bullet collide to enemy
function b_e_collide(goli,enemy){
//blast
blast=this.game.add.sprite(enemy.x,enemy.y,'blast');
blast.anchor.setTo(0.5);
blast.scale.setTo(0.5);
var explosion=blast.animations.add('explosion');
blast.animations.play('explosion',30,false,true);
//killing
goli.kill();
enemy.kill();
//update scores
if(enemy.no<4)
{
score+=1;
killed_sound.play('killed');
}
this.scoreText.text = 'Kills: ' + score;
}
//runs when ship collide to enemy
function s_e_collide(ship,enemy){
blast=this.game.add.sprite(enemy.x,enemy.y,'blast');
blast.anchor.setTo(0.5);
blast.scale.setTo(0.5);
var explosion=blast.animations.add('explosion');
blast.animations.play('explosion',10,false,true);
ship.kill();
enemy.kill();
//music.stop();
this.scoreText.kill();
death_music.play("death_music");
game.time.events.remove(fireLoop);
game.time.events.add(Phaser.Timer.SECOND * 2, function() {
fianlScore = this.game.add.text(this.game.world.centerX,this.game.world.centerY, 'KILL: '+score, { fontSize: '32px', fill: 'yellow' });
fianlScore.anchor.setTo(0.5);
gameOverText = this.game.add.text(this.game.world.centerX,this.game.world.centerY - fianlScore.height, 'GAME OVER', { fontSize: '32px', fill: 'red' });
gameOverText.anchor.setTo(0.5);
//restart button
restart=this.game.add.sprite(this.game.world.centerX,this.game.world.centerY + fianlScore.height+10,'restart');
restart.anchor.setTo(0.5);
restart.scale.setTo(0.05,0.05);
restart.inputEnabled = true;
restart.events.onInputDown.add(restartGame, this);
game.time.events.stop();
}, this);
}
//runs when ship collide power1
function s_power1_collide(ship,power){
power.kill();
game.time.events.remove(fireLoop);
fireLoop=game.time.events.loop(Phaser.Timer.SECOND*1/10, fireBullet, this);
game.time.events.add(Phaser.Timer.SECOND * 10, function(){
game.time.events.remove(fireLoop);
fireLoop=game.time.events.loop(Phaser.Timer.SECOND*1/buttetSpwanSpeed, fireBullet, this);
},this);
}
function changeEnemySpeed()
{
if(enemySpeed<=900)
{
enemySpeed+=5;
}
if(enemySpwanSpeed<=3)
{
enemySpwanSpeed+=0.025;
}
enemyLoop.delay=Phaser.Timer.SECOND*1/enemySpwanSpeed;
}
//send power up
function powerFun()
{
x1=game.rnd.integerInRange(0,this.game.world.width);
x2=game.rnd.integerInRange(0,this.game.world.width);
power=this.game.add.sprite(x1,10,'power1');
power.anchor.setTo(0.5);
var shine=power.animations.add('shine');
power.animations.play('shine',5,true,true);
power.checkWorldBounds = true;
power.outOfBoundsKill = true;
powers.add(power);
game.physics.arcade.enable(power);
power.body.collisonWorldBounds=true;
game.physics.arcade.moveToXY(power, x2, this.game.world.height+power.height, 400,0);
powerDelay=game.rnd.integerInRange(20,35);
powerUp.delay=Phaser.Timer.SECOND*powerDelay;
}
function restartGame(){
setStart();
game.time.events.start();
game.state.start("PreGameState");
}
game.state.add("GameState",GameState);
game.state.add("BootState",BootState);
game.state.add("LoadingState",LoadingState);
game.state.add("PreGameState",PreGameState);
game.state.start("BootState");
since the game is so small in size I think it should run smoothly on mobile devices.
it runs good on some high end mobile devices but gets slow as time progresses.
this is my first game so I am not very good with game designing concepts.
Hi I currently got this issue fixed myself for my games cross platform.
Things I did were
Load alll sprites right at my main screen/or loading screen
If you have reusable sprites use the command .kill() not .destory() which will take more memory to reload sprite unless the sprite is not coming back to screen then it’s ok to destroy.
Recycle everything let’s say you use a bullet asoon as it hits the wall boom kill and get it back.
And sad part in some cases even by doing sometimes it’ll still lag and have some glitches here and there you just have to see at what point is happening. Use break points to see exactly what sprites are causing it and consider also if the image doesn’t have transparency to use .jpeg
Good luck hope this helps
If it works fine on your desktop, most likely it's an issue with the asset sizes being too big. Reduce all of your assets 1/2 of the size. Phaser has to load all of the assets into cache, then it reduces the pixel size of those files in the engine.
In the mobile phone the processing capacity is lower than in the desktop.
Generally the architecture of a mobile Cpu is usually optimized to save energy. When you are on a desktop, the x86 or x64 architecture is optimized for processing of data.
Therefore it is very important to test the performance of the application on the target device.
You need to reduce creation of objects, loading images or objects when the game is playing. I have better experience with my game just hidging and showing the same objects (enemies), instead of destroying objects (Enemies or Visual elements) and creating again while play. Because when a game create a new instance, the CPU load the same again. This change no make diference in high CPU but is very better in low CPU. Maybe it help you.

Paper undefined in JS function using Raphael

Alright, so I am having a bit of trouble with Raphael and automatic updating of elements.
I've got a file called objects.js which looks something like this:
window.onload = function() {
paper = Raphael(document.getElementById('ikoner'), 600, 200);
pump = paper.circle(50,100,50);
pump.data("id","pump");
pump.data("tag",':="output".tag5:');
}
function objectFill (table) {
paper.forEach(function(e){
var tagValue = e.tag.innerHTML;
var tagId = e.id.innerHTML.trim();
if (tagValue == 0) {
paper.getById(tagId).attr({fill:"white"});
}
}
}
On my main page I've got a script which then calls objectFill on a certain interval, and updates the fill color of my objects.
Now to the problem; when I run the page I get the error that paper is undefined in objectFill. How do I make sure that objectFill will be able to find the paper? I've also tried declaring it outside like:
var paper;
window.onload = function() {
paper = Raphael(document.getElementById('ikoner'), 600, 200);
}
But I do not get that to work either. Anyone know what the problem might be?

Spine multiple animations

So I have 2, or more skeletons for an animation (so, 2 or more json files). I want them to play at the same time and 10 seconds after, to play another animation.
Problem is that there is only one animation playing, and the second isn't displayed.
The way I'm doing it is the following:
<canvas id="animationCanvas" width="240" height="240"></canvas>
<script>
var first = true,
rendererFirst = new spine.SkeletonRenderer('http://someurl.com/images/'),
spineAFirst = /* My JSON Code */,
parsedFirst = JSON.parse(spineAFirst);
rendererFirst.scale = 0.2;
rendererFirst.load(spineAFirst);
rendererFirst.state.data.defaultMix = 1.0;
for (var i in parsedFirst.animations) {
if (first) {
first = false;
rendererFirst.state.setAnimationByName(0, i, true);
} else {
rendererFirst.state.addAnimationByName(0, i, true, 10);
}
}
rendererFirst.skeleton.x = 120;
rendererFirst.skeleton.y = 120;
rendererFirst.animate('animationCanvas');
</script>
And, of course, I'm doing it twice (or more). I tried as well with a single SkeletonRenderer, just loading (and setting or adding) animations as many times as I need, and it didn't worked.
It seems that the renderer is cleaning the canvas each time it is called, the better way to achieve this seems to create a canvas for each animation, and bind a renderer to each one.

JavaScript game loop playing catch up/blury/ghosted in chrome/browsers

I have been trying to set up a javascript game loop and I have two issues I am running into. I find that in chrome when I lose focus of the browser window and then click back the animation I have running does this weird "catch up" thing where it quickly runs through the frames it should of been rendering in the background. I also have noticed that the animation is blury when moving at the current speed I have it at yet other people have been able to get their canvas drawings to move quickly and still look crisp. I know their seems to be a lot out about this but I cant make sense of what my issue really is. I thought this was a recommended way to create a game loop.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Frame Test</title>
<link href="/css/bootstrap.css" media="all" rel="stylesheet" type="text/css" />
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"
type="text/javascript">
</script>
<script language="javascript" src="js/jquery.hotkeys.js" type="text/javascript"></script>
<script language="javascript" src="js/key_status.js" type="text/javascript"></script>
<script language="javascript" src="js/util.js" type="text/javascript"></script>
<script language="javascript" src="js/sprite.js" type="text/javascript"></script>
</head>
<body>
<button id="button1">
Toggle Loop</button>
<h1 id="frameCount">
Game Loop Test</h1>
<canvas id="gameCanvas" width="800" height="500">
<p>Your browser doesn't support canvas.</p>
</canvas>
<script type='text/javascript'>
// demo code used for playing around with javascript-canvas animations
var frameCount = 0;
var drawingCanvas = document.getElementById('gameCanvas');
// Check the element is in the DOM and the browser supports canvas
if (drawingCanvas.getContext) {
var context = drawingCanvas.getContext('2d');
var x = 100;
var y = 100;
var right = true;
context.strokeStyle = "#000000";
context.fillStyle = "Green";
context.beginPath();
context.arc(x, y, 50, 0, Math.PI * 2, true);
context.closePath();
context.stroke();
context.fill();
}
function Timer(settings) {
this.settings = settings;
this.timer = null;
this.on = false; //Bool that represents if the timer is running or stoped
this.fps = settings.fps || 30; //Target frames per second value
this.interval = Math.floor(1000 / 30);
this.timeInit = null; //Initial time taken when start is called
return this;
}
Timer.prototype =
{
run: function () {
var $this = this;
this.settings.run();
this.timeInit += this.interval;
this.timer = setTimeout(
function () { $this.run() },
this.timeInit - (new Date).getTime()
);
},
start: function () {
if (this.timer == null) {
this.timeInit = (new Date).getTime();
this.run();
this.on = true;
}
},
stop: function () {
clearTimeout(this.timer);
this.timer = null;
this.on = false;
},
toggle: function () {
if (this.on) { this.stop(); }
else { this.start(); }
}
}
var timer = new Timer({
fps: 30,
run: function () {
//---------------------------------------------run game code here------------------------------------------------------
//Currently Chorme is playing a catch up game with the frames to be drawn when the user leaves the browser window and then returns
//A simple canvas animation is drawn here to try and figure out how to solve this issue. (Most likely related to the timer implimentation)
//Once figured out probably the only code in this loop should be something like
//updateGameLogic();
//updateGameCanvas();
frameCount++;
if (drawingCanvas.getContext) {
// Initaliase a 2-dimensional drawing context
//Canvas commands go here
context.clearRect((x - 52), 48, (x + 52), 104);
// Create the yellow face
context.strokeStyle = "#000000";
context.fillStyle = "Green";
context.beginPath();
if (right) {
x = x + 6;
if (x > 500)
right = false;
} else {
x = x - 6;
if (x < 100)
right = true;
}
context.arc(x, 100, 50, 0, Math.PI * 2, true);
context.closePath();
context.stroke();
context.fill();
}
document.getElementById("frameCount").innerHTML = frameCount;
//---------------------------------------------end of game loop--------------------------------------------------------
}
});
document.getElementById("button1").onclick = function () { timer.toggle(); };
frameCount++;
document.getElementById("frameCount").innerHTML = frameCount;
</script>
</body>
</html>
-------------Update ---------------------
I have used requestanimation frame and that has solved the frame rate problam but I still get weird ghosting/bluring when the animation is running. any idea how I should be drawing this thing?
Okay, so part of your problem is that when you switch tabs, Chrome throttles down its performance.
Basically, when you leave, Chrome slows all of the calculations on the page to 1 or 2 fps (battery-saver, and more performance for the current tab).
Using setTimeout in the way that you have is basically scheduling all of these calls, which sit and wait for the user to come back (or at most are only running at 1fps).
When the user comes back, you've got hundreds of these stacked calls, waiting to be handled, and because they've all been scheduled earlier, they've all passed their "wait" time, so they're all going to execute as fast as possible (fast-forward), until the stack is emptied to where you have to start waiting 32ms for the next call.
A solution to this is to stop the timer when someone leaves -- pause the game.
On some browsers which support canvas games in meaningful ways, there is also support for a PageVisibility API. You should look into it.
For other browsers, it'll be less simple, but you can tie to a blur event on the window for example.
Just be sure that when you restart, you also clear your interval for your updates.
Ultimately, I'd suggest moving over to `requestAnimationFrame, because it will intelligently handle frame rate, and also handle the throttling you see, due to the stacked calls, but your timer looks like a decent substitute for browsers which don't yet have it.
As for blurriness, that needs more insight.
Reasons off the top of my head, if you're talking about images, are either that your canvas' width/height are being set in CSS, somewhere, or your sprites aren't being used at a 1:1 scale from the image they're pulled from.
It can also come down to sub-pixel positioning of your images, or rotation.
Hope that helps a little.
...actually, after looking at your code again, try removing "width" and "height" from your canvas in HTML, and instead, change canvas.width = 800; canvas.height = 500; in JS, and see if that helps any.

Categories

Resources