inherit the createjs.Container from easeljs library - javascript

I am using Easeljs in my spare time. I tried to inherit the Container from createjs object in easeljs library.
var innovative = {};
innovative.object = {};
innovative.object.Basic = function () {
};
//innovative.object.Basic.prototype = new createjs.Container;
innovative.object.LocalPhoto = function (data) {
};
innovative.object.LocalPhoto.prototype = new innovative.object.Basic;
innovative.object.LocalPhoto.prototype.constructor = innovative.object.LocalPhoto;
I have function in LocalPhoto which will add itself to the stage like this
innovative.object.LocalPhoto.prototype.load = function (stage, event) {
var self = this;
stage.addChild(self);
stage.update();
};
This is how i create LocalPhoto object
var self = this;
for (var i = 0; i < values.length; i++) {
this.download (values[i], function (evt) {
var photo;
photo = new innovative.object.LocalPhoto(evt.target.object);
photo.load(self.stage, evt);
});
}
Problem i am facing is when i add a LocalPhoto into the stage, the rest of the localPhoto within that stage will append the same photo as well.
This is what i mean in steps : 1) insert a image within a container and added to the stage.
2) another image within a new container and added to the stage.
At the same time, the later image also added to the other child container which i have added to the stage.

(function() {
function YourFunc(param) {
this.Container_constructor();
this.param = param;
}
var p = createjs.extend(YourFunc, createjs.Container);
p.draw = function() {
this.Container_draw();
// add custom logic here.
}
window.Button = createjs.promote(Button, "Container");
}());
Or Just
var p = YourFunc.prototype = new createjs.Container();

Related

Win Pivot App. Need to access some data from a section. Any ideas?

I have a JavaScript Win Pivot Application
Into the Hub I am retrieving some information:
function initPages(options) {
for (var i = 0; i < options.length ; i++) {
var menuItem = options[i];
menuItem.showBanner = (i == 0);
definePages(options);
}
}
and in a .Js file I have the definePages function created:
functions.js:
function definePages(item) {
var action = item[0];
var animation = item[1];
var scyfy = item[2];
var localmovies = item[3];
var clasic = item[4];
var comedy = item[5];
var biography = item[6];
var drama = item[7];
var kids = item[8];
var musical = item[9];
var romantic = item[10];
var suspense = item[11];
var horror = item[12];
var art = item[13];
var personalities = item[14];
var history = item[15];
var society = item[16];
}
Now, in my section 1 I initialize the page by calling another function there:
ready: function (element, options) {
// TODO: Inicializar la página aquí.
options = options || {};
initMovies();
},
function initMovies() {
var element = document.getElementById("movieContainer");
//var movies = ??????????????????????????
//console.log(movies);
//it keeps going
}
I need to be able to retrive, in that var movies, the var action, from the functions.Js or, which is the same, the items[0]...
However, if I call a function in functions.Js, which is defined in section1Page, it won´t work...
I can call functions and pass data from anywhere to functions.Js, but not the other way around...
Any ideas on what should I do? Thanks!!!
I fixed it... I created a global var in function.Js and I get the info from the array in each section later on:
function definePages(item) {
tooSleepyToThink = item;
}
section1Page:
function initMovies() {
var elemento = document.getElementById("movieContainer");
console.log(tooSleepyToThink[0].text);
}

oop - How to get this of this javascript

I'm changing some code to function more like a class in c# so I don't have to make a new script for each occurrence. I've hit problems with my scope on my constructors, I have this constructor
function Game(canvas) {
this.Polygon = function(size, pointCount){
this.size = size;
this.pointCount = pointCount;
this.corners = [];
this.palette = [];
this.render = function (GameObject) {
this.makePolygon(GameObject, this.size, this.corners);
};
};
this.makePolygon = function(GameObject, size, corners){//other code...}
}
My problem is in this.render, makePolygon is inside the class so this means something different. I have tried using .bind(this); but I can't get it to work.
I'm positive that this has been asked before but none of the answers I found would work for me.
A convention that I have used on different teams is to alias this at the top of javascript functions, to avoid this exact problem.
Example:
this.Polygon = function(size, pointCount){
var my = this;
my.size = size;
my.pointCount = pointCount;
my.corners = [];
my.palette = [];
my.render = function (GameObject) {
my.makePolygon(GameObject, my.size, my.corners);
};
};
this.makePolygon = function(GameObject, size, corners){//other code...}
Another option, depending on where this function lies, is to do it as follows.
// Somewhere at the top of this code snippet
var my = this;
//...
my.Polygon = function(size, pointCount){
my.size = size;
my.pointCount = pointCount;
my.corners = [];
my.palette = [];
my.render = function (GameObject) {
my.makePolygon(GameObject, my.size, my.corners);
};
};
my.makePolygon = function(GameObject, size, corners){//other code...}

Issue related to Registering Event in For loop

I have small application in Famo.us framework. I have added four images in mainContext with draggable modifier using four loop. I want fire an event when user drag the event for that I have added following code.
var Engine = require('famous/core/Engine');
var Surface = require('famous/core/Surface');
var Transform = require('famous/core/Transform');
var MouseSync = require("famous/inputs/MouseSync");
var StateModifier = require('famous/modifiers/StateModifier');
var Draggable = require("famous/modifiers/Draggable");
var ImageSurface = require('famous/surfaces/ImageSurface');
var Transitionable = require("famous/transitions/Transitionable");
var SnapTransition = require("famous/transitions/SnapTransition");
Transitionable.registerMethod('snap', SnapTransition);
// create the main context
var mainContext = Engine.createContext();
var mouseSync = new MouseSync();
var isPlus;
var isFirst = true;
var oldValues = [];
var mySurfaces=[];
var draggables = [];
var myModifiers= [];
var images = [
['img/svelteMan.png', -0.4375 * window.innerWidth, -1.5 * window.innerWidth],
['img/swimmer.png', 0 * window.innerWidth, -0.96875 * window.innerWidth],
['img/soccerPlayer.png', -0.21875 * window.innerWidth, -0.984375 * window.innerWidth],
['img/breakDancer.png', 0 * window.innerWidth, -0.6875 * window.innerWidth]
];
for(var i=0;i<images.length;i++) {
var mySurface = new ImageSurface({ });
mySurface.setContent(images[i][0]);
var myModifier = new StateModifier({
origin: [0.5, 0.5]
});
var draggable = new Draggable({ });
mySurface.pipe(draggable);
mySurfaces.push(mySurface);
myModifiers.push(myModifier);
draggables.push(draggable);
mainContext.add(draggables[i]).add(myModifiers[i]).add(mySurfaces[i]);
var oldValue =0;
oldValues.push(oldValue);
}
ActivateEvent();
function ActivateEvent(){
for(var i=0;i<images.length;i++) {
draggables[i].on('update', function (data) {
MakeMove(i);
});
}
};
function MakeMove(i) {
//alert(i);
if (oldValues[i] > draggables[i].getPosition()[0]) {
myModifiers[i].setTransform(Transform.rotateZ(-0.1));
} else {
myModifiers[i].setTransform(Transform.rotateZ(0.1));
}
oldValues[i] = draggables[i].getPosition()[0];
}
I have added onUpdate event of Draggable as following :
for(var i=0;i<images.length;i++) {
draggables[i].on('update', function (data) {
MakeMove(i);
});
}
But I am getting error saying draggables[i] is not defined
If I want to call an event of Third image on draggable then how to call event? How to register an events when surfaces added in for loop?
Thanks
Add a closure:
var cl = function(n) {
return function(data){
MakeMove(n);
};
};
for(var i=0;i<images.length;i++)
{
draggables[i].on('update', cl(i));
}
Hope it helps.
You have a closure problem.
Take a look of this:
var draggables = [];
for(i=0;i<10;i++) {
var draggable = new Draggable({ });
draggables.push(draggable);
}
ActivateEvent();
function ActivateEvent(){
for(var i=0;i<10;i++) {
setTimeout(function() {
MakeMove(i);
}(i),0); //<----- notice the (i), this how you can send the correct loop for MakeMove function, without that (i) the anonymous function scope breaks the loop
}
}
function MakeMove(i) {
console.log(draggables[i]); //==> this outputs the draggables
}
Maybe you can try this:
draggables[i].on('update', function (data) {
MakeMove(i);
}(i)); <----- now the loop is send to makeMove

Html5/javascript/easeljs game project.Lots of code.I need a way out

I am working on a card game with HTML5 canvas and javascript with create.js library. The problem i have is that, I have an onclick function that deletes the clicked card from player's hand(removes the object from the array with splice and then redraws the canvas/redraws on canvas the new array of player's cards without the deleted one). When i do this for first time it does well.But if I click again on the card that it should be for example at index 1 in the array(after the splice method) it doesn't work.
Look at this code:
Here is my code for class Card:
function Card(suit,rank,imageFrontUrl,imageBackUrl)
{
this.imageFront = new createjs.Bitmap(imageFrontUrl);
this.imageBack = new createjs.Bitmap(imageBackUrl);
this.suit = suit;
this.rank = rank;
}
function Deck(){
this.cards = new Array();
this.makeDeck = function()
{
this.cards[0]= new Card("clubs",1,"images/114.png","images/155.png");
this.cards[1]= new Card("clubs",2,"images/115.png","images/155.png");
this.cards[2]= new Card("clubs",3,"images/116.png","images/155.png");
this.cards[3]= new Card("clubs",4,"images/117.png","images/155.png");
this.cards[4]= new Card("clubs",5,"images/118.png","images/155.png");
this.cards[5]= new Card("clubs",6,"images/119.png","images/155.png");
...
}
this.shuffleDeck = function()
{
var j,k;
for (j = 0; j < this.cards.length; j++) {
k = Math.floor(Math.random() * this.cards.length);
temp = this.cards[j];
this.cards[j] = this.cards[k];
this.cards[k] = temp;
}
}
this.dealCardsPlayer = function()
{
var playerDeck = new Array();
for(var i = 0; i<6;i++)
{
var x = this.cards.pop();
playerDeck.push(x);
}
return playerDeck;
}
}
Here is my code for class Player:
function Player()
{
this.playerTurn = false;
this.id = this;
this.name = this;
this.score = this;
this.playerHand = new Array();
this.playerTakenCards = new Array();
this.playerPickCard = function(n)
{
var card = this.playerHand(n);
return card;
}
this.tempArray = this;}
Here is my init function:
function init(){
var canvas = document.getElementById("tutorialCanvas");
var stage = new createjs.Stage(canvas);
var deck = new Deck();
var player1 = new Player();
deck.makeDeck();
deck.shuffleDeck();
player1.playerHand = deck.dealCardsPlayer();
function drawPlayerCards(){
var rotation=280;
for(var i =0;i<player1.playerHand.length;i++)
{
player1.playerHand[i].imageFront.x=330;
player1.playerHand[i].imageFront.y=750;
player1.playerHand[i].imageFront.regX = 0;
player1.playerHand[i].imageFront.regY = 96;
player1.playerHand[i].imageFront.rotation = rotation;
rotation = player1.playerHand[i].imageFront.rotation+20;
stage.addChild(player1.playerHand[i].imageFront);
}
}
createjs.Ticker.addEventListener("tick", stage);}
And here is the function i have problem with:
player1.playerHand[1].imageFront.addEventListener('click',function(event)
{
stage.removeAllChildren();
player1.playerHand.splice(1,1);
drawTableDeck();
drawPlayerCards();
}
After some researching I realized that the function works just for the first bitmap player1.playerHand[1].imageFront . If i change the array with the first onclick event and after that player1.playerHand[1].imageFront is some other image/bitmap, it doesn't work for it. Please help!
Why are you "hardcoding" the index of a card in your hand?
player1.playerHand.forEach(function(card) {
card.imageFront.addEventListener("click", function() {
var index = player1.playerHand.indexOf(card);
if (index != -1) {
stage.removeAllChildren();
player1.playerHand.splice(index, 1);
drawPlayerCards();
}
});
});
Some other notes:
It's a convention to use [] instead of new Array()
We normally put the opening brace { on the same line
Your Player constructor has an error: this.playerHand[n] instead of this.playerHand(n)

Cloned objects and reference inside functions

I am trying to do the following:
var element = {};
element.attrA = 'A';
element.attrB = 1;
element.autoAdvance = function(){
var that = this;
setInterval(function(){
that.attrB++;
},100);
}
element.instance = function(){
var clone = $.extend(true, {}, this);
return clone;
}
Now I can do the following just fine:
var e1 = element.instance();
var e2 = element.instance();
e1.attrA = 'not e2s business';
e2.attrA = 'not e1s attrA';
The trouble starts when I try to use autoAdvance:
e1.autoAdvance();
will start the autoAdvance for all cloned 'instances' of element. I am sure this is probably rather trivial but I just don't know how to refer to the parent object inside my autoAdvance-function in a way that it gets properly cloned and only affects the instance. Thanks!
EDIT:
This is the actual code I am using:
var player = {};
player.sprites = {};
player.sprites.back = ['img/playerback_01.png','img/playerback_02.png','img/playerback_03.png'];
player.sprites.head = ['img/playerhead_01.png','img/playerhead_02.png','img/playerhead_03.png'];
player.back = new Image();
player.back.src = player.sprites.back[0];
player.head = new Image();
player.head.src = player.sprites.head[0];
player.loop = function(){
var that = this;
var loop = setInterval(function(){
//remove the [0] state from the sprite array and add it at [2]
var state = that.sprites.head.shift();
that.sprites.head.push(state);
state = that.sprites.back.shift();
that.sprites.back.push(state);
that.back.src = that.sprites.back[0];
that.head.src = that.sprites.head[0];
}, 100);
}
player.x = 0;
player.y = 0;
player.instance = function(){
var clone = $.extend(true, {}, this);
return clone;
}
I generate two players:
var player1 = player.instance();
var player2 = player.instance();
But what is happening is that when I use:
player1.loop();
The animation for player2 will start to play as well.
I suggest you start using "class" in JavaScript. They are more or less a function.
function Player(){
this.sprites={};
......
}
Player.prototype.loop=function(){
....
}
var player1=new Player();
var player2=new Player();
player1.loop();
player2.loop();// this should work better
It doesn't really answer your question but it's an alternative way to write code in a cleaner and better way.

Categories