How to trigger createjs animation on slick slider afterchange callback? - javascript

I am using slick carousel slider which has 5 slides, each slide should trigger an animation after it gets displayed on the page.
An animator has created an animation using Adobe Animate CC and exported the animation in createjs format so it is compatible with html5.
If I try to call the animation on afterchange I get an error:
TypeError: lib.FlowerGrowTemplate is not a constructor
See the comment below for where the error is happening:
/*The error is pointing to here*/
Adobe Animate CC generated javascript code:
(function (cjs, an) {
var p; // shortcut to reference prototypes
var lib={};var ss={};var img={};
lib.ssMetadata = [];
// symbols:
// helper functions:
function mc_symbol_clone() {
var clone = this._cloneProps(new this.constructor(this.mode, this.startPosition, this.loop));
clone.gotoAndStop(this.currentFrame);
clone.paused = this.paused;
clone.framerate = this.framerate;
return clone;
}
function getMCSymbolPrototype(symbol, nominalBounds, frameBounds) {
var prototype = cjs.extend(symbol, cjs.MovieClip);
prototype.clone = mc_symbol_clone;
prototype.nominalBounds = nominalBounds;
prototype.frameBounds = frameBounds;
return prototype;
}
.....
})(createjs = createjs||{}, AdobeAn = AdobeAn||{});
var createjs, AdobeAn;
var graphic_canvas_1, graphic_stage_1, graphic_exportRoot_1, graphic_container_1, graphic_dom_overlay_container_1, graphic_fnStartAnimation_1;
function graphic_init_1() {
graphic_canvas_1 = document.getElementById("graphic_canvas");
graphic_container_1 = document.getElementById("graphic_container");
graphic_dom_overlay_container_1 = document.getElementById("graphic_dom_overlay_container");
var comp=AdobeAn.getComposition("AD6FD640782B2A4DAD43D647860AC61B");
var lib=comp.getLibrary();
graphic_handleComplete_1({},comp);
}
function graphic_handleComplete_1(evt,comp) {
//This function is always called, irrespective of the content. You can use the variable "stage" after it is created in token create_stage.
var lib=comp.getLibrary();
var ss=comp.getSpriteSheet();
graphic_exportRoot_1 = new lib.FlowerGrowTemplate(); /*The error is pointing to here*/
graphic_stage_1 = new lib.Stage(graphic_canvas_1);
//Registers the "tick" event listener.
graphic_fnStartAnimation_1 = function() {
graphic_stage_1.addChild(graphic_exportRoot_1);
createjs.Ticker.setFPS(lib.properties.fps);
createjs.Ticker.addEventListener("tick", graphic_stage_1)
graphic_stage_1.addEventListener("tick", graphic_handleTick_1)
function graphic_getProjectionMatrix_1(container, totalDepth) {
var focalLength = 528.25;
var projectionCenter = { x : lib.properties.width/2, y : lib.properties.height/2 };
var scale = (totalDepth + focalLength)/focalLength;
var scaleMat = new createjs.Matrix2D;
scaleMat.a = 1/scale;
scaleMat.d = 1/scale;
var projMat = new createjs.Matrix2D;
projMat.tx = -projectionCenter.x;
projMat.ty = -projectionCenter.y;
projMat = projMat.prependMatrix(scaleMat);
projMat.tx += projectionCenter.x;
projMat.ty += projectionCenter.y;
return projMat;
}
function graphic_handleTick_1(event) {
var cameraInstance = graphic_exportRoot_1.___camera___instance;
if(cameraInstance !== undefined && cameraInstance.pinToObject !== undefined)
{
cameraInstance.x = cameraInstance.pinToObject.x + cameraInstance.pinToObject.pinOffsetX;
cameraInstance.y = cameraInstance.pinToObject.y + cameraInstance.pinToObject.pinOffsetY;
if(cameraInstance.pinToObject.parent !== undefined && cameraInstance.pinToObject.parent.depth !== undefined)
cameraInstance.depth = cameraInstance.pinToObject.parent.depth + cameraInstance.pinToObject.pinOffsetZ;
}
graphic_applyLayerZDepth_1(graphic_exportRoot_1);
}
function graphic_applyLayerZDepth_1(parent)
{
var cameraInstance = parent.___camera___instance;
var focalLength = 528.25;
var projectionCenter = { 'x' : 0, 'y' : 0};
if(parent === graphic_exportRoot_1)
{
var stageCenter = { 'x' : lib.properties.width/2, 'y' : lib.properties.height/2 };
projectionCenter.x = stageCenter.x;
projectionCenter.y = stageCenter.y;
}
for(child in parent.children)
{
var layerObj = parent.children[child];
if(layerObj == cameraInstance)
continue;
graphic_applyLayerZDepth_1(layerObj, cameraInstance);
if(layerObj.layerDepth === undefined)
continue;
if(layerObj.currentFrame != layerObj.parent.currentFrame)
{
layerObj.gotoAndPlay(layerObj.parent.currentFrame);
}
var matToApply = new createjs.Matrix2D;
var cameraMat = new createjs.Matrix2D;
var totalDepth = layerObj.layerDepth ? layerObj.layerDepth : 0;
var cameraDepth = 0;
if(cameraInstance && !layerObj.isAttachedToCamera)
{
var mat = cameraInstance.getMatrix();
mat.tx -= projectionCenter.x;
mat.ty -= projectionCenter.y;
cameraMat = mat.invert();
cameraMat.prependTransform(projectionCenter.x, projectionCenter.y, 1, 1, 0, 0, 0, 0, 0);
cameraMat.appendTransform(-projectionCenter.x, -projectionCenter.y, 1, 1, 0, 0, 0, 0, 0);
if(cameraInstance.depth)
cameraDepth = cameraInstance.depth;
}
if(layerObj.depth)
{
totalDepth = layerObj.depth;
}
//Offset by camera depth
totalDepth -= cameraDepth;
if(totalDepth < -focalLength)
{
matToApply.a = 0;
matToApply.d = 0;
}
else
{
if(layerObj.layerDepth)
{
var sizeLockedMat = graphic_getProjectionMatrix_1(parent, layerObj.layerDepth);
if(sizeLockedMat)
{
sizeLockedMat.invert();
matToApply.prependMatrix(sizeLockedMat);
}
}
matToApply.prependMatrix(cameraMat);
var projMat = graphic_getProjectionMatrix_1(parent, totalDepth);
if(projMat)
{
matToApply.prependMatrix(projMat);
}
}
layerObj.transformMatrix = matToApply;
}
}
}
//Code to support hidpi screens and responsive scaling.
function graphic_makeResponsive_1(isResp, respDim, isScale, scaleType) {
var lastW, lastH, lastS=1;
window.addEventListener('resize', graphic_resizeCanvas_1);
graphic_resizeCanvas_1();
function graphic_resizeCanvas_1() {
var w = lib.properties.width, h = lib.properties.height;
var iw = window.innerWidth, ih=window.innerHeight;
var pRatio = window.devicePixelRatio || 1, xRatio=iw/w, yRatio=ih/h, sRatio=1;
if(isResp) {
if((respDim=='width'&&lastW==iw) || (respDim=='height'&&lastH==ih)) {
sRatio = lastS;
}
else if(!isScale) {
if(iw<w || ih<h)
sRatio = Math.min(xRatio, yRatio);
}
else if(scaleType==1) {
sRatio = Math.min(xRatio, yRatio);
}
else if(scaleType==2) {
sRatio = Math.max(xRatio, yRatio);
}
}
graphic_canvas_1.width = w*pRatio*sRatio;
graphic_canvas_1.height = h*pRatio*sRatio;
graphic_canvas_1.style.width = graphic_dom_overlay_container_1.style.width = graphic_container_1.style.width = w*sRatio+'px';
graphic_canvas_1.style.height = graphic_container_1.style.height = graphic_dom_overlay_container_1.style.height = h*sRatio+'px';
graphic_stage_1.scaleX = pRatio*sRatio;
graphic_stage_1.scaleY = pRatio*sRatio;
lastW = iw; lastH = ih; lastS = sRatio;
graphic_stage_1.tickOnUpdate = false;
graphic_stage_1.update();
graphic_stage_1.tickOnUpdate = true;
}
}
graphic_makeResponsive_1(false,'both',false,1);
AdobeAn.compositionLoaded(lib.properties.id);
graphic_fnStartAnimation_1();
}
My javascript code:
(function($){
$('.custom-graphic-slider .slider').slick({
slidesToShow: 1,
slidesToScroll: 1,
arrows: false,
dots: true,
fade: true,
});
$('.custom-graphic-slider .slider').on('afterChange', function(event, slick, currentSlide){
graphic_init_1();
});
})(jQuery);
I hope everything makes sense

Related

TweenJS animation not working

I am working on a tool to perform sequence of animations by updating an object array. This array would have all the parameters to customize animation as per varied requirements. This tool is being developed with JavaScript and makes use of createJS library and TweenJS to animate objects. Objects are created dynamically and positioned, then the tween is applied. Tween doesn't seem to work in my code.
I have the whole code below
var AnimationFlow = (function () {
'use strict';
var AnimationFlow = function (canvasID) {
this.canvas = document.getElementById(canvasID);
this.stage = new createjs.Stage(this.canvas);
this.timeline = new createjs.Timeline();
this.tween = [];
this.preload;
this.animData;
this.manifest = [];
this.animObject = [];
this.stageObject = [];
this.loadProgressLabel;
this.loadingBarContainer;
this.loadingBar;
};
AnimationFlow.prototype.setData = function (data) {
this.animData = data;
this.manifest = [];
this.renderProgressBar();
for (var i = 0; i < this.animData.length; i++) {
this.manifest.push({'src': this.animData[i].targeturl, 'id': this.animData[i].targetID});
}
};
AnimationFlow.prototype.init = function () {
createjs.Ticker.addEventListener("tick", this.tick.bind(this));
createjs.Ticker.setFPS(30);
createjs.Ticker.useRAF = true;
this.preload = new createjs.LoadQueue(false);
this.preload.addEventListener("complete", this.handleComplete.bind(this));
this.preload.addEventListener("progress", this.handleProgress.bind(this));
this.preload.loadManifest(this.manifest);
this.stage.update();
};
AnimationFlow.prototype.handleProgress = function () {
this.loadingBar.scaleX = this.preload.progress * this.loadingBarWidth;
this.progresPrecentage = Math.round(this.preload.progress * 100);
this.loadProgressLabel.text = this.progresPrecentage + "% Loaded";
this.stage.update();
};
AnimationFlow.prototype.handleComplete = function () {
//Load images logic to be added
for (var i = 0; i < this.manifest.length; i++) {
this.animObject.push(this.preload.getResult(this.manifest[i].id));
}
this.loadProgressLabel.text = "Loading complete click to start";
this.stage.update();
this.canvas.addEventListener("click", this.handleClick.bind(this));
};
AnimationFlow.prototype.handleClick = function () {
this.start();
this.stage.removeChild(this.loadProgressLabel, this.loadingBarContainer);
this.canvas.removeEventListener("click", this.handleClick);
};
AnimationFlow.prototype.start = function () {
for (var i = 0; i < this.animObject.length; i++) {
this.obj = new createjs.Bitmap(this.animObject[i]);
this.obj.x = this.animData[i].initialXPos;
this.obj.y = this.animData[i].initialYPos;
this.obj.visible = this.animData[i].initialVisibility;
this.stage.addChild(this.obj);
this.stageObject.push(this.obj);
if(this.animData[i].isAnimatable){
var c = createjs.Tween.get(this.obj);
c.to({x:this.animData[i].params.xpos}, this.animData[i].duration);
c.call(this.tweenComplete);
this.timeline.addTween(c);
}
}
this.stage.update();
};
AnimationFlow.prototype.tick = function () {
console.log("heart beat on....");
this.stage.update();
};
AnimationFlow.prototype.tweenComplete = function () {
console.log("tweenComplete.......");
};
AnimationFlow.prototype.renderProgressBar = function () {
this.loadProgressLabel = new createjs.Text("", "18px Verdana", "black");
this.loadProgressLabel.lineWidth = 200;
this.loadProgressLabel.textAlign = "center";
this.loadProgressLabel.x = this.canvas.width / 2;
this.loadProgressLabel.y = 50;
this.stage.addChild(this.loadProgressLabel);
this.loadingBarContainer = new createjs.Container();
this.loadingBarHeight = 20;
this.loadingBarWidth = 300;
this.LoadingBarColor = createjs.Graphics.getRGB(0, 0, 0);
this.loadingBar = new createjs.Shape();
this.loadingBar.graphics.beginFill(this.LoadingBarColor).drawRect(0, 0, 1, this.loadingBarHeight).endFill();
this.frame = new createjs.Shape();
this.padding = 3;
this.frame.graphics.setStrokeStyle(1).beginStroke(this.LoadingBarColor).drawRect(-this.padding / 2, -this.padding / 2, this.loadingBarWidth + this.padding, this.loadingBarHeight + this.padding);
this.loadingBarContainer.addChild(this.loadingBar, this.frame);
this.loadingBarContainer.x = Math.round(this.canvas.width / 2 - this.loadingBarWidth / 2);
this.loadingBarContainer.y = 100;
this.stage.addChild(this.loadingBarContainer);
};
return AnimationFlow;
})();
var data = [{targetID: 'background', targeturl: 'assets/images/heliGame/sky.png',isAnimatable:true, duration: 2000, params: {xpos: '600'}, isVisibleAfterAnimation: true, isVisibleAtStartAnimation: true, initialVisibility: true, initialXPos: '0', initialYPos: '0'},
{targetID: 'mousePointer', targeturl: 'assets/images/heliGame/helicopter.png',isAnimatable:true, duration: 1000, params: {xpos: '500'}, isVisibleAfterAnimation: false, isVisibleAtStartAnimation: true, initialVisibility: true, initialXPos: '0', initialYPos: '0'}];
var buttons = ["playPauseBtn", "startFirstBtn", "reverseBtn"];
var animTool = new AnimationFlow('testCanvas');
animTool.setData(data);
animTool.init();
I have the code in JSFiddle
https://jsfiddle.net/jamesshaji/t4pxzsoo/
There were a couple of issues. Firstly, you need to define all of your positions as integers and not as strings (ie: take the quotes off of your position data in your data object). Secondly, you need to call: this.timeline.gotoAndPlay(0); to start the timeline execution. Otherwise the animations won't play. Here is a fixed version:
var AnimationFlow = (function() {
'use strict';
var AnimationFlow = function(canvasID) {
this.canvas = document.getElementById(canvasID);
this.stage = new createjs.Stage(this.canvas);
this.timeline = new createjs.Timeline();
this.tween = [];
this.preload;
this.animData;
this.manifest = [];
this.animObject = [];
this.stageObject = [];
this.loadProgressLabel;
this.loadingBarContainer;
this.loadingBar;
};
AnimationFlow.prototype.setData = function(data) {
this.animData = data;
this.manifest = [];
this.renderProgressBar();
for (var i = 0; i < this.animData.length; i++) {
this.manifest.push({
'src': this.animData[i].targeturl,
'id': this.animData[i].targetID
});
}
};
AnimationFlow.prototype.init = function() {
createjs.Ticker.addEventListener("tick", this.tick.bind(this));
createjs.Ticker.setFPS(30);
createjs.Ticker.useRAF = true;
this.preload = new createjs.LoadQueue(false);
this.preload.addEventListener("complete", this.handleComplete.bind(this));
this.preload.addEventListener("progress", this.handleProgress.bind(this));
this.preload.loadManifest(this.manifest);
this.stage.update();
};
AnimationFlow.prototype.handleProgress = function() {
this.loadingBar.scaleX = this.preload.progress * this.loadingBarWidth;
this.progresPrecentage = Math.round(this.preload.progress * 100);
this.loadProgressLabel.text = this.progresPrecentage + "% Loaded";
this.stage.update();
};
AnimationFlow.prototype.handleComplete = function() {
//Load images logic to be added
for (var i = 0; i < this.manifest.length; i++) {
this.animObject.push(this.preload.getResult(this.manifest[i].id));
}
this.loadProgressLabel.text = "Loading complete click to start";
this.stage.update();
this.canvas.addEventListener("click", this.handleClick.bind(this));
};
AnimationFlow.prototype.handleClick = function() {
this.start();
this.stage.removeChild(this.loadProgressLabel, this.loadingBarContainer);
this.canvas.removeEventListener("click", this.handleClick);
};
AnimationFlow.prototype.start = function() {
for (var i = 0; i < this.animObject.length; i++) {
this.obj = new createjs.Bitmap(this.animObject[i]);
this.obj.x = this.animData[i].initialXPos;
this.obj.y = this.animData[i].initialYPos;
this.obj.visible = this.animData[i].initialVisibility;
this.stage.addChild(this.obj);
this.stageObject.push(this.obj);
if (this.animData[i].isAnimatable) {
console.log("animatable:" + this.animData[i].params.xpos + " " + this.animData[i].duration);
var c = createjs.Tween.get(this.obj);
c.to({
x: this.animData[i].params.xpos
}, this.animData[i].duration);
c.call(this.tweenComplete);
this.timeline.addTween(c);
}
}
this.timeline.gotoAndPlay(0);
this.stage.update();
};
AnimationFlow.prototype.tick = function() {
this.stage.update();
};
AnimationFlow.prototype.tweenComplete = function() {
console.log("tweenComplete.......");
};
AnimationFlow.prototype.renderProgressBar = function() {
this.loadProgressLabel = new createjs.Text("", "18px Verdana", "black");
this.loadProgressLabel.lineWidth = 200;
this.loadProgressLabel.textAlign = "center";
this.loadProgressLabel.x = this.canvas.width / 2;
this.loadProgressLabel.y = 50;
this.stage.addChild(this.loadProgressLabel);
this.loadingBarContainer = new createjs.Container();
this.loadingBarHeight = 20;
this.loadingBarWidth = 300;
this.LoadingBarColor = createjs.Graphics.getRGB(0, 0, 0);
this.loadingBar = new createjs.Shape();
this.loadingBar.graphics.beginFill(this.LoadingBarColor).drawRect(0, 0, 1, this.loadingBarHeight).endFill();
this.frame = new createjs.Shape();
this.padding = 3;
this.frame.graphics.setStrokeStyle(1).beginStroke(this.LoadingBarColor).drawRect(-this.padding / 2, -this.padding / 2, this.loadingBarWidth + this.padding, this.loadingBarHeight + this.padding);
this.loadingBarContainer.addChild(this.loadingBar, this.frame);
this.loadingBarContainer.x = Math.round(this.canvas.width / 2 - this.loadingBarWidth / 2);
this.loadingBarContainer.y = 100;
this.stage.addChild(this.loadingBarContainer);
};
return AnimationFlow;
})();
var data = [{
targetID: 'background',
targeturl: 'https://s13.postimg.org/tyj4iop93/Sky_Pic.jpg',
isAnimatable: true,
duration: 2000,
params: {
xpos: -100
},
isVisibleAfterAnimation: true,
isVisibleAtStartAnimation: true,
initialVisibility: true,
initialXPos: 0,
initialYPos: 0
}, {
targetID: 'mousePointer',
targeturl: 'http://jamesshaji.com/angular/assets/images/heliGame/helicopter.png',
isAnimatable: true,
duration: 2000,
params: {
xpos: 100
},
isVisibleAfterAnimation: false,
isVisibleAtStartAnimation: true,
initialVisibility: true,
initialXPos: 450,
initialYPos: 50
}];
var buttons = ["playPauseBtn", "startFirstBtn", "reverseBtn"];
var animTool = new AnimationFlow('testCanvas');
animTool.setData(data);
animTool.init();
<script src="https://code.createjs.com/createjs-2015.11.26.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tweenjs/0.6.2/tweenjs.min.js"></script>
<div>Animation</div>
<canvas height="500" width="500" id="testCanvas">
</canvas>

Multiplayer coins

Having a slight issue getting some coins to generate multiplayer using eureca.io websockets. I've got the players working multiplayer and from remote connections but I can't seem to get the coins to generate across the connection so they appear in the same place on all the players connections. I'm using phaser to generate the game and eureca and engine for my web connection. I've got the coins to spawn on the page with no problems, but whenever a new player joins, the coin always displays in a different place, I wondering how I can make them generate across the connection. My game code is below:
Game Code
var myId = 0;
var background;
var blueSquare;
var player;
var coins;
var goldCoin;
var squareList;
var coinList;
var cursors;
var score;
var highScore;
var ready = false;
var eurecaServer;
var eurecaClientSetup = function () {
var eurecaClient = new Eureca.Client();
eurecaClient.ready(function (proxy) {
eurecaServer = proxy;
});
eurecaClient.exports.setId = function (id)
{
myId = id;
create();
eurecaServer.handshake();
ready = true;
}
eurecaClient.exports.kill = function (id)
{
if (squareList[id]) {
squareList[id].kill();
console.log('Player has left the game ', id, squareList[id]);
}
}
eurecaClient.exports.spawnBlueSquare = function (i, x, y)
{
if (i == myId) return;
console.log('A new player has joined the game');
var blsq = new BlueSquare(i, game, blueSquare);
squareList[i] = blsq;
}
eurecaClient.exports.spawnCoins = function (c, x, y)
{
console.log('A coin has been generated');
var cn = new GenerateCoin(c, game, coin);
coinList[c] = cn;
}
eurecaClient.exports.updateState = function (id, state)
{
if (squareList[id]) {
squareList[id].cursor = state;
squareList[id].blueSquare.x = state.x;
squareList[id].blueSquare.y = state.y;
squareList[id].blueSquare.angle = state.angle;
squareList[id].update();
coinList.cursor = state;
coinList.blueSquare.x = state.x;
coinList.blueSquare.y = state.y;
coinList.update();
}
}
}
BlueSquare = function (index, game, player) {
this.cursor = {
left:false,
right:false,
up:false,
down:false,
}
this.input = {
left:false,
right:false,
up:false,
down:false,
}
var x = 0;
var y = 0;
this.game = game;
this.player = player;
this.currentSpeed = 0;
this.isBlue = true;
this.blueSquare = game.add.sprite(x, y, 'blueSquare');
this.blueSquare.anchor.set(0.5);
this.blueSquare.id = index;
game.physics.enable(this.blueSquare, Phaser.Physics.ARCADE);
this.blueSquare.body.immovable = false;
this.blueSquare.body.collideWorldBounds = true;
this.blueSquare.body.setSize(34, 34, 0, 0);
this.blueSquare.angle = 0;
game.physics.arcade.velocityFromRotation(this.blueSquare.rotation, 0, this.blueSquare.body.velocity);
}
BlueSquare.prototype.update = function () {
var inputChanged = (
this.cursor.left != this.input.left ||
this.cursor.right != this.input.right ||
this.cursor.up != this.input.up ||
this.cursor.down != this.input.down
);
if (inputChanged)
{
if (this.blueSquare.id == myId)
{
this.input.x = this.blueSquare.x;
this.input.y = this.blueSquare.y;
this.input.angle = this.blueSquare.angle;
eurecaServer.handleKeys(this.input);
}
}
if (this.cursor.left)
{
this.blueSquare.body.velocity.x = -250;
this.blueSquare.body.velocity.y = 0;
}
else if (this.cursor.right)
{
this.blueSquare.body.velocity.x = 250;
this.blueSquare.body.velocity.y = 0;
}
else if (this.cursor.down)
{
this.blueSquare.body.velocity.x = 0;
this.blueSquare.body.velocity.y = 250;
}
else if (this.cursor.up)
{
this.blueSquare.body.velocity.x = 0;
this.blueSquare.body.velocity.y = -250;
}
else
{
this.blueSquare.body.velocity.x = 0;
this.blueSquare.body.velocity.y = 0;
}
}
BlueSquare.prototype.kill = function () {
this.alive = false;
this.blueSquare.kill();
}
GenerateCoin = function (game, goldCoin) {
this.game = game;
this.goldCoin = goldCoin;
x = 0;
y = 0;
this.coins = game.add.sprite(x, y, 'coin');
game.physics.enable(this.coins, Phaser.Physics.ARCADE);
this.coins.body.immovable = true;
this.coins.body.collideWorldBounds = true;
this.coins.body.setSize(16, 16, 0, 0);
}
window.onload = function() {
function countdown( elementName, minutes, seconds )
{
var element, endTime, hours, mins, msLeft, time;
function twoDigits( n )
{
return (n <= 9 ? "0" + n : n);
}
function updateTimer()
{
msLeft = endTime - (+new Date);
if ( msLeft < 1000 ) {
element.innerHTML = "Game Over!";
} else {
time = new Date( msLeft );
hours = time.getUTCHours();
mins = time.getUTCMinutes();
element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() );
setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
}
}
element = document.getElementById( elementName );
endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
updateTimer();
}countdown( "countdown", 5, 0 );
}
var game = new Phaser.Game(700, 600, Phaser.AUTO, 'Square Hunt', { preload: preload, create: eurecaClientSetup, update: update, render: render });
function preload () {
game.load.spritesheet('coin', 'assets/coin.png', 18, 18);
game.load.image('blueSquare', 'assets/blue-square.png');
game.load.image('redSquare', 'assets/red-square.png');
game.load.image('earth', 'assets/sand.png');
}
function create () {
game.world.setBounds(0, 0, 1500, 1500);
game.stage.disableVisibilityChange = true;
background = game.add.tileSprite(0, 0, 800, 600, 'earth');
background.fixedToCamera = true;
squareList = {};
player = new BlueSquare(myId, game, blueSquare);
squareList[myId] = player;
blueSquare = player.blueSquare;
blueSquare.x = Math.floor(Math.random() * 650);
blueSquare.y = Math.floor(Math.random() * 650);
blueSquare.bringToTop();
game.camera.follow(blueSquare);
game.camera.deadzone = new Phaser.Rectangle(150, 150, 500, 300);
game.camera.focusOnXY(0, 0);
cursors = game.input.keyboard.createCursorKeys();
coinList = {};
goldCoin = new GenerateCoin(game, coins);
coinList = goldCoin;
coins = goldCoin.coins;
coins.x = Math.floor(Math.random() * 650);
coins.y = Math.floor(Math.random() * 650);
coins.bringToTop();
}
function update () {
if (!ready) return;
game.physics.arcade.collide(blueSquare, coins);
player.input.left = cursors.left.isDown;
player.input.right = cursors.right.isDown;
player.input.up = cursors.up.isDown;
player.input.down = cursors.down.isDown;
player.input.fire = game.input.activePointer.isDown;
player.input.tx = game.input.x+ game.camera.x;
player.input.ty = game.input.y+ game.camera.y;
background.tilePosition.x = -game.camera.x;
background.tilePosition.y = -game.camera.y;
for (var i in squareList)
{
if (!squareList[i]) continue;
var curBlue = squareList[i].blueSquare;
for (var j in squareList)
{
if (!squareList[j]) continue;
if (j!=i)
{
var targetBlue = squareList[j].blueSquare;
}
if (squareList[j].isBlue)
{
squareList[j].update();
}
}
}
}
function test(){
console.log('collsion');
}
function render () {}
Server.js Files
var express = require('express')
, app = express(app)
, server = require('http').createServer(app);
app.use(express.static(__dirname));
var clients = {};
var EurecaServer = require('eureca.io').EurecaServer;
var eurecaServer = new EurecaServer({allow:['setId', 'spawnBlueSquare', 'spawnCoins', 'kill', 'updateState']});
eurecaServer.attach(server);
eurecaServer.onConnect(function (conn) {
console.log('New Client id=%s ', conn.id, conn.remoteAddress);
var remote = eurecaServer.getClient(conn.id);
clients[conn.id] = {id:conn.id, remote:remote}
remote.setId(conn.id);
});
eurecaServer.onConnectionLost(function (conn) {
console.log('connection lost ... will try to reconnect');
});
eurecaServer.onDisconnect(function (conn) {
console.log('Client disconnected ', conn.id);
var removeId = clients[conn.id].id;
delete clients[conn.id];
for (var c in clients)
{
var remote = clients[c].remote;
remote.kill(conn.id);
}
});
eurecaServer.exports.handshake = function()
{
for (var c in clients)
{
var remote = clients[c].remote;
for (var cc in clients)
{
var x = clients[cc].laststate ? clients[cc].laststate.x: 0;
var y = clients[cc].laststate ? clients[cc].laststate.y: 0;
remote.spawnBlueSquare(clients[cc].id, x, y);
}
}
}
eurecaServer.exports.handleKeys = function (keys) {
var conn = this.connection;
var updatedClient = clients[conn.id];
for (var c in clients)
{
var remote = clients[c].remote;
remote.updateState(updatedClient.id, keys);
clients[c].laststate = keys;
}
}
server.listen(8000);
Instead of generating coins randomly positioned on each client, you could generate this random position(x and y) in server side(on conexion event) and then send this position to all clients so they can generate the coin in the same position.

How do I create an animated tile in pixi.js with good performance?

How can I use PIXI js to animate from spritesheets using TiledSprites? I need to animate a tiled sprite background from a sprite sheet.
Currently there is API calls to animate a tiled sprite in the PIXI.js API. I have created the following class to help me load and animate tiled backgrounds.
/////////////////////////////////////////////////////////////////////////////
/// Tiling Sprite Animation
/////////////////////////////////////////////////////////////////////////////
(function() {
PIXI.TilingSpriteAnimation = function(texture, frames, rows, frametime, loop) {
PIXI.TilingSprite.call(
this, texture,
VIEWPORTWIDTH,
this._texture.baseTexture.height);
this._stop = true;
this._texture = new PIXI.Texture(texture);
this.frameTime = frametime;
this.loop = loop || true;
this.curX = 0;
this.curY = 0;
this.fh = this._texture.height / rows;
this.fw = this._texture.width / frames;
this.ticks = 0;
this.maxFrames = frames;
this.maxRows = rows;
this.done = false;
this.calculateFrame();
};
PIXI.TilingSpriteAnimation.prototype = Object.create( PIXI.TilingSprite.prototype );
PIXI.TilingSpriteAnimation.prototype.constructor = PIXI.TilingSpriteAnimation;
Object.defineProperty(PIXI.TilingSpriteAnimation.prototype, 'texture', {
get: function() {
return this._texture;
}
});
PIXI.TilingSpriteAnimation.prototype.update = function() {
console.log(this.ticks);
if(!this._stop) {
this.ticks += 1;
}
if (this.done == false) {
if (this.ticks >= this.frameTime) {
this.curX++;
this.ticks = 0;
if (this.curX == this.maxFrames) {
this.curX = 0;
this.curY++;
if (this.curY == this.maxRows) {
this.curY = 0;
if (!this.loop)
this.done = true;
}
}
this.calculateFrame();
}
}
};
PIXI.TilingSpriteAnimation.prototype.goto = function(frame, row) {
this.curX = frame;
this.curY = row || 0;
};
PIXI.TilingSpriteAnimation.prototype.stop = function() {
this._stop = true;
};
PIXI.TilingSpriteAnimation.prototype.play = function() {
this._stop = false;
};
PIXI.TilingSpriteAnimation.prototype.calculateFrame = function() {
this.texture.frame.x = this.curX * this.fw;
this.texture.frame.y = this.curY * this.fh;
this.texture.frame.width = this.fw;
this.texture.frame.height = this.fh;
this.texture.setFrame(this.texture.frame);
this.generateTilingTexture(this.texture);
};
}).call(this);
This code is however highly inefficient because it calculates a new TiledTexture each time a new frame is entered. How can I optimize this?
I struggeled some time with this but came up with the following. I hope it helps
/////////////////////////////////////////////////////////////////////////////
/// Tiling Sprite Animation
/////////////////////////////////////////////////////////////////////////////
(function() {
PIXI.TilingSpriteAnimation = function(texture, frames, frametime, loop) {
PIXI.TilingSprite.call(
this, texture,
VIEWPORTWIDTH,
VIEWPORTHEIGHT);
this._stop = true;
this._texture = new PIXI.Texture(texture);
this.frameTime = frametime;
this.loop = loop || true;
this.curX = 0;
this.fh = this._texture.height;
this.fw = this._texture.width / frames;
this.ticks = 0;
this.maxFrames = frames;
for (var i=0;i<frames;i++){
this.preLoadFrame(i);
}
this.calculateFrame();
};
PIXI.TilingSpriteAnimation.prototype = Object.create( PIXI.TilingSprite.prototype );
PIXI.TilingSpriteAnimation.prototype.constructor = PIXI.TilingSpriteAnimation;
Object.defineProperty(PIXI.TilingSpriteAnimation.prototype, 'texture', {
get: function() {
return this._texture;
}
});
PIXI.TilingSpriteAnimation.prototype.update = function() {
if (this._stop == false) {
this.ticks += 1;
if (this.ticks >= this.frameTime) {
this.curX++;
this.ticks = 0;
if (this.curX == this.maxFrames) {
this.curX = 0;
if (!this.loop) {
this._stop = true;
}
}
this.calculateFrame();
}
}
};
PIXI.TilingSpriteAnimation.prototype.goto = function(frame) {
this.curX = frame;
};
PIXI.TilingSpriteAnimation.prototype.stop = function() {
this._stop = true;
};
PIXI.TilingSpriteAnimation.prototype.play = function() {
this._stop = false;
};
PIXI.TilingSpriteAnimation.prototype.calculateFrame = function() {
this.tilingTexture = PIXI.Texture.fromFrame("texture" + this.curX);
};
PIXI.TilingSpriteAnimation.prototype.preLoadFrame = function(frame) {
var text = new PIXI.TilingSprite(this.texture);
text.texture.frame.x = frame * this.fw;
text.texture.frame.y = 0;
text.texture.frame.width = this.fw;
text.texture.frame.height = this.fh;
text.texture.setFrame(text.texture.frame);
text.generateTilingTexture(text);
PIXI.Texture.addTextureToCache(text.tilingTexture, "texture" + frame)
};
}).call(this);

Cannot fix Syntax error: Unexpected token '<'

I have been trying to fix a piece of javascript code but am not having any luck. The syntax looks correct but I keep getting an unexpected token '<' syntax error.
Please do not mark this question as a duplicate since I could not find the answer to my problem on this site.
Javascript:
// Function to get elements by class name for DOM fragment and tag name
function getElementsByClassName(objElement, strTagName, strClassName)
{
var objCollection = objElement.getElementsByTagName(strTagName);
var arReturn = [];
var strClass, arClass, iClass, iCounter;
for(iCounter=0; iCounter<objCollection.length; iCounter++)
{
strClass = objCollection[iCounter].className;
if (strClass)
{
arClass = strClass.split(' ');
for (iClass=0; iClass<arClass.length; iClass++)
{
if (arClass[iClass] == strClassName)
{
arReturn.push(objCollection[iCounter]);
break;
}
}
}
}
objCollection = null;
return (arReturn);
}
var drag = {
objCurrent : null,
arTargets : ['Fav', 'Tol', 'Rej'],
initialise : function(objNode)
{
// Add event handlers
objNode.onmousedown = drag.start;
objNode.onclick = function() {this.focus();};
objNode.onkeydown = drag.keyboardDragDrop;
document.body.onclick = drag.removePopup;
},
keyboardDragDrop : function(objEvent)
{
objEvent = objEvent || window.event;
drag.objCurrent = this;
var arChoices = ['Favourite artists', 'Tolerable artists', 'Rejected artists'];
var iKey = objEvent.keyCode;
var objItem = drag.objCurrent;
var strExisting = objItem.parentNode.getAttribute('id');
var objMenu, objChoice, iCounter;
if (iKey == 32)
{
document.onkeydown = function(){return objEvent.keyCode==38 || objEvent.keyCode==40 ? false : true;};
// Set ARIA properties
drag.objCurrent.setAttribute('aria-grabbed', 'true');
drag.objCurrent.setAttribute('aria-owns', 'popup');
// Build context menu
objMenu = document.createElement('ul');
objMenu.setAttribute('id', 'popup');
objMenu.setAttribute('role', 'menu');
for (iCounter=0; iCounter<arChoices.length; iCounter++)
{
if (drag.arTargets[iCounter] != strExisting)
{
objChoice = document.createElement('li');
objChoice.appendChild(document.createTextNode(arChoices[iCounter]));
objChoice.tabIndex = -1;
objChoice.setAttribute('role', 'menuitem');
objChoice.onmousedown = function() {drag.dropObject(this.firstChild.data.substr(0, 3));};
objChoice.onkeydown = drag.handleContext;
objChoice.onmouseover = function() {if (this.className.indexOf('hover') < 0) {this.className += ' hover';} };
objChoice.onmouseout = function() {this.className = this.className.replace(/\s*hover/, ''); };
objMenu.appendChild(objChoice);
}
}
objItem.appendChild(objMenu);
objMenu.firstChild.focus();
objMenu.firstChild.className = 'focus';
drag.identifyTargets(true);
}
},
removePopup : function()
{
document.onkeydown = null;
var objContext = document.getElementById('popup');
if (objContext)
{
objContext.parentNode.removeChild(objContext);
}
},
handleContext : function(objEvent)
{
objEvent = objEvent || window.event;
var objItem = objEvent.target || objEvent.srcElement;
var iKey = objEvent.keyCode;
var objFocus, objList, strTarget, iCounter;
// Cancel default behaviour
if (objEvent.stopPropagation)
{
objEvent.stopPropagation();
}
else if (objEvent.cancelBubble)
{
objEvent.cancelBubble = true;
}
if (objEvent.preventDefault)
{
objEvent.preventDefault();
}
else if (objEvent.returnValue)
{
objEvent.returnValue = false;
}
switch (iKey)
{
case 38 : // Down arrow
objFocus = objItem.nextSibling;
if (!objFocus)
{
objFocus = objItem.previousSibling;
}
objItem.className = '';
objFocus.focus();
objFocus.className = 'focus';
break;
case 40 : // Up arrow
objFocus = objItem.previousSibling;
if (!objFocus)
{
objFocus = objItem.nextSibling;
}
objItem.className = '';
objFocus.focus();
objFocus.className = 'focus';
break;
case 13 : // Enter
strTarget = objItem.firstChild.data.substr(0, 3);
drag.dropObject(strTarget);
break;
case 27 : // Escape
case 9 : // Tab
drag.objCurrent.removeAttribute('aria-owns');
drag.objCurrent.removeChild(objItem.parentNode);
drag.objCurrent.focus();
for (iCounter=0; iCounter<drag.arTargets.length; iCounter++)
{
objList = document.getElementById(drag.arTargets[iCounter]);
drag.objCurrent.setAttribute('aria-grabbed', 'false');
objList.removeAttribute('aria-dropeffect');
objList.className = '';
}
break;
}
},
start : function(objEvent)
{
objEvent = objEvent || window.event;
drag.removePopup();
// Initialise properties
drag.objCurrent = this;
drag.objCurrent.lastX = objEvent.clientX;
drag.objCurrent.lastY = objEvent.clientY;
drag.objCurrent.style.zIndex = '2';
drag.objCurrent.setAttribute('aria-grabbed', 'true');
document.onmousemove = drag.drag;
document.onmouseup = drag.end;
drag.identifyTargets(true);
return false;
},
drag : function(objEvent)
{
objEvent = objEvent || window.event;
// Calculate new position
var iCurrentY = objEvent.clientY;
var iCurrentX = objEvent.clientX;
var iYPos = parseInt(drag.objCurrent.style.top, 10);
var iXPos = parseInt(drag.objCurrent.style.left, 10);
var iNewX, iNewY;
iNewX = iXPos + iCurrentX - drag.objCurrent.lastX;
iNewY = iYPos + iCurrentY - drag.objCurrent.lastY;
drag.objCurrent.style.left = iNewX + 'px';
drag.objCurrent.style.top = iNewY + 'px';
drag.objCurrent.lastX = iCurrentX;
drag.objCurrent.lastY = iCurrentY;
return false;
},
calculatePosition : function (objElement, strOffset)
{
var iOffset = 0;
// Get offset position in relation to parent nodes
if (objElement.offsetParent)
{
do
{
iOffset += objElement[strOffset];
objElement = objElement.offsetParent;
} while (objElement);
}
return iOffset;
},
identifyTargets : function (bHighlight)
{
var strExisting = drag.objCurrent.parentNode.getAttribute('id');
var objList, iCounter;
// Highlight the targets for the current drag item
for (iCounter=0; iCounter<drag.arTargets.length; iCounter++)
{
objList = document.getElementById(drag.arTargets[iCounter]);
if (bHighlight && drag.arTargets[iCounter] != strExisting)
{
objList.className = 'highlight';
objList.setAttribute('aria-dropeffect', 'move');
}
else
{
objList.className = '';
objList.removeAttribute('aria-dropeffect');
}
}
},
getTarget : function()
{
var strExisting = drag.objCurrent.parentNode.getAttribute('id');
var iCurrentLeft = drag.calculatePosition(drag.objCurrent, 'offsetLeft');
var iCurrentTop = drag.calculatePosition(drag.objCurrent, 'offsetTop');
var iTolerance = 40;
var objList, iLeft, iRight, iTop, iBottom, iCounter;
for (iCounter=0; iCounter<drag.arTargets.length; iCounter++)
{
if (drag.arTargets[iCounter] != strExisting)
{
// Get position of the list
objList = document.getElementById(drag.arTargets[iCounter]);
iLeft = drag.calculatePosition(objList, 'offsetLeft') - iTolerance;
iRight = iLeft + objList.offsetWidth + iTolerance;
iTop = drag.calculatePosition(objList, 'offsetTop') - iTolerance;
iBottom = iTop + objList.offsetHeight + iTolerance;
// Determine if current object is over the target
if (iCurrentLeft > iLeft && iCurrentLeft < iRight && iCurrentTop > iTop && iCurrentTop < iBottom)
{
return drag.arTargets[iCounter];
}
}
}
// Current object is not over a target
return '';
},
dropObject : function(strTarget)
{
var objClone, objOriginal, objTarget, objEmpty, objBands, objItem;
drag.removePopup();
if (strTarget.length > 0)
{
// Copy node to new target
objOriginal = drag.objCurrent.parentNode;
objClone = drag.objCurrent.cloneNode(true);
// Remove previous attributes
objClone.removeAttribute('style');
objClone.className = objClone.className.replace(/\s*focused/, '');
objClone.className = objClone.className.replace(/\s*hover/, '');
// Add focus indicators
objClone.onfocus = function() {this.className += ' focused'; };
objClone.onblur = function() {this.className = this.className.replace(/\s*focused/, '');};
objClone.onmouseover = function() {if (this.className.indexOf('hover') < 0) {this.className += ' hover';} };
objClone.onmouseout = function() {this.className = this.className.replace(/\s*hover/, ''); };
objTarget = document.getElementById(strTarget);
objOriginal.removeChild(drag.objCurrent);
objTarget.appendChild(objClone);
drag.objCurrent = objClone;
drag.initialise(objClone);
// Remove empty node if there are artists in list
objEmpty = getElementsByClassName(objTarget, 'li', 'empty');
if (objEmpty[0])
{
objTarget.removeChild(objEmpty[0]);
}
// Add an empty node if there are no artists in list
objBands = objOriginal.getElementsByTagName('li');
if (objBands.length === 0)
{
objItem = document.createElement('li');
objItem.appendChild(document.createTextNode('None'));
objItem.className = 'empty';
objOriginal.appendChild(objItem);
}
}
// Reset properties
drag.objCurrent.style.left = '0px';
drag.objCurrent.style.top = '0px';
drag.objCurrent.style.zIndex = 'auto';
drag.objCurrent.setAttribute('aria-grabbed', 'false');
drag.objCurrent.removeAttribute('aria-owns');
drag.identifyTargets(false);
},
end : function()
{
var strTarget = drag.getTarget();
drag.dropObject(strTarget);
document.onmousemove = null;
document.onmouseup = null;
drag.objCurrent = null;
}
};
function init ()
{
var objItems = getElementsByClassName(document, 'li', 'draggable');
var objItem, iCounter;
for (iCounter=0; iCounter<objItems.length; iCounter++)
{
// Set initial values so can be moved
objItems[iCounter].style.top = '0px';
objItems[iCounter].style.left = '0px';
// Put the list items into the keyboard tab order
objItems[iCounter].tabIndex = 0;
// Set ARIA attributes for artists
objItems[iCounter].setAttribute('aria-grabbed', 'false');
objItems[iCounter].setAttribute('aria-haspopup', 'true');
objItems[iCounter].setAttribute('role', 'listitem');
// Provide a focus indicator
objItems[iCounter].onfocus = function() {this.className += ' focused'; };
objItems[iCounter].onblur = function() {this.className = this.className.replace(/\s*focused/, '');};
objItems[iCounter].onmouseover = function() {if (this.className.indexOf('hover') < 0) {this.className += ' hover';} };
objItems[iCounter].onmouseout = function() {this.className = this.className.replace(/\s*hover/, ''); };
drag.initialise(objItems[iCounter]);
}
// Set ARIA properties on the drag and drop list, and set role of this region to application
for (iCounter=0; iCounter<drag.arTargets.length; iCounter++)
{
objItem = document.getElementById(drag.arTargets[iCounter]);
objItem.setAttribute('aria-labelledby', drag.arTargets[iCounter] + 'h');
objItem.setAttribute('role', 'list');
}
objItem = document.getElementById('dragdrop');
objItem.setAttribute('role', 'application');
objItems = null;
}
window.onload = init;
This type of problem usually occurs when issuing an AJAX request which expects JSON or JavaScript as a response but it receives HTML in stead.
When expecting JSON or JavaScript the text of the response must be "eval"-uated by a JavaScript parser. If HTML code is received and evaluated as JSON or JavaScript, the presence of a lower than < or a greater than > symbol will cause errors.

Simple function call inside module, getting NaN, huh?

Here is the module i am working on:
var FeatureRotator = (function($,global) {
var self = {},
currentFeature = 0,
images = [],
imagePrefix = "/public/images/features/",
timer = null,
totalImages = 0,
initialFeature,
interval,
blendSpeed,
element = null,
img1 = null,
img2 = null;
function setVisibleImage(iid) {
$("#img1").attr('src',images[iid].src).css('opacity',1);
$("#img2").css('opacity',0);
$(".active").removeClass("active");
$("#f"+iid).addClass("active");
}
function setCurrentImage(id) {
currentFeature = id;
setVisibleImage(id);
}
function doHoverIn(position) {
if (currentFeature === position) {
self.pause();
} else {
setCurrentImage(global.parseInt(position, 10));
self.pause();
}
}
function doHoverOut(position) {
self.unpause();
}
self.init = function(options,callback) {
var i = 0,
tempImg = null;
interval = options.interval || 5000;
blendSpeed = options.blendSpeed || 500;
element = options.element;
initialFeature = options.initialFeature || 0;
img1 = $("<img/>").attr('id','img1');
img2 = $("<img/>").attr('id','img2').css('opacity','0').css('margin-top',-options.height);
$(element).append(img1).append(img2);
totalImages = $(".feature").size();
for (i = 0;i < totalImages; i++) {
tempImg = new global.Image();
tempImg.src = imagePrefix +"feature_" + i + ".png";
images.push(tempImg);
$("#f"+i).css('background-image',
'url("'+imagePrefix+"feature_"+i+"_thumb.png"+'")')
.hover(doHoverIn($(this).attr('position'))
, doHoverOut($(this).attr('position'))
).attr('position',i);
}
setVisibleImage(initialFeature);
if (options.autoStart) {
self.start();
}
if (callback !== null) {
callback();
}
};
function updateImage() {
var active = $("#img1").css('opacity') === 1 ? "#img1" : "#img2";
var nextFeature = (currentFeature === totalImages-1 ? 0 : currentFeature+1);
if (active === "#img1") {
$("#img2").attr('src',images[nextFeature].src);
$("#img2").fadeTo(blendSpeed, 1);
$("#img1").fadeTo(blendSpeed, 0);
} else {
$("#img1").attr('src',images[nextFeature].src);
$("#img1").fadeTo(blendSpeed, 1);
$("#img2").fadeTo(blendSpeed, 0);
}
$("#f"+currentFeature).removeClass("active");
$("#f"+nextFeature).addClass("active");
currentFeature = nextFeature;
}
self.start = function() {
currentFeature = initialFeature;
setVisibleImage(currentFeature);
timer = global.setInterval(function(){
updateImage();
}, interval);
};
self.pause = function() {
global.clearTimeout(timer);
};
self.unpause = function() {
timer = global.setInterval(function(){
updateImage();
}, interval);
};
return self;
}(this.jQuery, this));
And here is how it is used on the page:
<script type="text/javascript">
// ...
$(function() {
FeatureRotator.init({
interval:5000,
element:'#intro',
autoStart:true,
height:177,
blendSpeed:1000,
initialFeature:0
});
});
</script>
The problem is, when setVisibleImage is called from the init method, the value of iid is NaN. I've stepped through the debugger and verified that 'initialFeature' is 0 when the setVisibleImage function is called, but alas, the value doesn't make it over there.
Can anyone help me determine what the problem is? I've run the code through JSLint, and it came back clean.
UPDATE
Ok here is my updated code, which works now except the fading doesnt work, the image just flips to the next one and doesn't fade smoothly anymore:
var FeatureRotator = (function($,global) {
var self = {},
currentFeature = 0,
images = [],
imagePrefix = "/public/images/features/",
timer = null,
totalImages = 0,
initialFeature = 0,
interval,
blendSpeed;
function setVisibleImage(iid) {
$("#img1").attr('src',images[iid].src).css('opacity',1);
$("#img2").css('opacity',0);
$(".active").removeClass("active");
$("#f"+iid).addClass("active");
}
function setCurrentImage(id) {
currentFeature = id;
setVisibleImage(id);
}
function doHoverIn(obj) {
var position = global.parseInt(obj.target.attributes["position"].value,10);
if (currentFeature === position) {
self.pause();
} else {
setCurrentImage(global.parseInt(position, 10));
self.pause();
}
}
function doHoverOut() {
self.unpause();
}
self.init = function(options,callback) {
var i = 0,
tempImg = null,
element = null,
img1 = null,
img2 = null;
interval = options.interval || 5000;
blendSpeed = options.blendSpeed || 500;
element = options.element;
initialFeature = options.initialFeature || 0;
img1 = $("<img/>").attr('id','img1');
img2 = $("<img/>").attr('id','img2').css('opacity','0').css('margin-top',-options.height);
$(element).append(img1).append(img2);
totalImages = $(".feature").size();
for (i = 0;i < totalImages; i++) {
tempImg = new global.Image();
tempImg.src = imagePrefix +"feature_" + i + ".png";
images.push(tempImg);
$("#f"+i).css('background-image','url("'+imagePrefix+"feature_"+i+"_thumb.png"+'")')
.hover(doHoverIn, doHoverOut)
.attr('position',i);
}
setVisibleImage(initialFeature);
if (options.autoStart) {
self.start();
}
if (typeof callback === "function") {
callback();
}
};
function updateImage() {
var active = $("#img1").css('opacity') === 1 ? "#img1" : "#img2";
var nextFeature = (currentFeature === totalImages-1 ? 0 : currentFeature+1);
if (active === "#img1") {
$("#img2").attr('src',images[nextFeature].src);
$("#img2").fadeTo(blendSpeed, 1);
$("#img1").fadeTo(blendSpeed, 0);
} else {
$("#img1").attr('src',images[nextFeature].src);
$("#img1").fadeTo(blendSpeed, 1);
$("#img2").fadeTo(blendSpeed, 0);
}
$("#f"+currentFeature).removeClass("active");
$("#f"+nextFeature).addClass("active");
currentFeature = nextFeature;
}
self.start = function() {
currentFeature = initialFeature;
setVisibleImage(currentFeature);
timer = global.setInterval(function(){
updateImage();
}, interval);
};
self.stop = function() {
global.clearTimeout(timer);
};
self.pause = function() {
global.clearTimeout(timer);
};
self.unpause = function() {
timer = global.setInterval(function(){
updateImage();
}, interval);
};
return self;
}(this.jQuery, this));
Since you're getting NaN, I'm guessing it is actually taking place from this line:
.hover(doHoverIn($(this).attr('position'))
...which calls this:
setCurrentImage(global.parseInt(position, 10)); // note the parseInt()
...which calls this:
setVisibleImage(id);
So the position being passed to parseInt is coming from $(this).attr('position'), which is likely an value that can't be parsed into a Number, so you get NaN.
Check out the value of that attribute in first line of the block for the for statement.
for (i = 0;i < totalImages; i++) {
console.log( $(this).attr('position') ); // verify the value of position
// ...

Categories

Resources