pageLoaded function not fired - javascript

I am creating todo app using nativescript javascript platform. please find the js code below. list items not showing in the landing page. while i tried to debug exports.pageloaded function not triggered. please point me what wents wrongs with the code. let me know if anything needed.
Thanks in advance!.
var Observable = require("tns-core-modules/data/observable");
var ObservableArray = require("tns-core-modules/data/observable-array");
var pageArray = new ObservableArray.ObservableArray();
var pageData = new Observable.Observable({
notes: pageArray
});
var view = require("tns-core-modules/ui/core/view");
var uiEnums = require("tns-core-modules/ui/enums");
var animation = require("tns-core-modules/ui/animation");
var appSettings = require("application-settings");
var fs = require("file-system");
var page;
var notesArr = [];
var current_index = -1;
exports.pageLoaded = function(args) {
page = args.object;
pageData.set('showForm', true);
var new_note_title = appSettings.getString('new_note_title');
var notes = appSettings.getString('notes');
if(!notes){
notes = [
{
index: 0,
title: '100 push ups'
},
{
index: 1,
title: '100 sit ups'
},
{
index: 2,
title: '100 squats'
},
{
index: 3,
title: '10km running'
}
];
}else{
notes = JSON.parse(notes);
}
notesArr = notes;
if(!pageArray.length){
for(var x = 0; x < notes.length; x++){
current_index += 1;
pageArray.push(notes[x]);
}
}
pageData.set('item_title', new_note_title);
args.object.bindingContext = pageData;
view.getViewById(page, 'form').animate({
translate: { x: 0, y: 160 },
duration: 800,
});
}
exports.newNote = function() {
var showForm = pageData.get('showForm');
var top_position = (showForm) ? -160 : 160;
var list_visibility = (showForm) ? 1 : 0;
view.getViewById(page, 'list').animate({
opacity: list_visibility,
duration: 400
});
view.getViewById(page, 'form').animate({
translate: { x: 0, y: top_position },
duration: 800,
});
pageData.set('showForm', !showForm);
}
exports.btnLoaded = function (args) {
var btn = args.object;
btn.android.setFocusable(false);
}
exports.saveNote = function() {
var new_note_title = pageData.get('item_title');
var new_note_photo = pageData.get('attachment_img');
current_index += 1;
var new_index = current_index;
var new_item = {
index: new_index,
title: new_note_title,
photo: new_note_photo,
show_photo: false
};
notesArr.push(new_item);
pageArray.push(new_item);
appSettings.setString('notes', JSON.stringify(notesArr));
appSettings.setNumber('current_index', new_index);
appSettings.remove('new_note_title');
appSettings.remove('new_note_photo');
pageData.set('showForm', false);
pageData.set('item_title', '');
pageData.set('attachment_img', null);
view.getViewById(page, 'list').animate({
opacity: 1,
duration: 400
});
view.getViewById(page, 'form').animate({
translate: { x: 0, y: -160 },
duration: 800,
});
}
exports.deleteNote = function(args){
var target = args.object;
var index_to_delete = notesArr.map(function(e) {
return e.index;
}).indexOf(target.index);
notesArr.map(function(item, index){
if(index == index_to_delete){
notesArr.splice(index_to_delete, 1);
pageArray.splice(index_to_delete, 1);
return false;
}
});
appSettings.setString('notes', JSON.stringify(notesArr));
}

Please find the playground here
function pageLoaded(args) {
alert('pageloaded');
...
}
and in the end
exports.pageLoaded = pageLoaded;
It is poping up the alert on load and pageLoaded function is getting fired.

Related

Scroll not works on mobile PIXI JS

I tried to make a canva which can scroll on mobile and desktop.
I have succeeded to scroll on desktop and even with touchpad, but i can't to find a way to scroll on my mobile.
I have already manage the scroll with mouse wheel but i haven't succeeded with touchscreen.
Do you have an idea to do work this below:
this.container = new PIXI.Container();
this.app.stage.addChild(this.container);
this.images = [t1, t2, t3, t4];
this.WHOLEWIDTH = this.images.length*(this.width + this.margin)
loadImages(this.images, (images)=>{
this.loadImages = images;
this.add()
this.render()
this.scrollEvent();
})
}
scrollEvent() {
document.addEventListener(
'mousewheel',
(e) => {
this.scrollTarget = e.wheelDelta / 3;
},
{ passive: true },
);
}
add() {
let parent = {
w: this.width,
h: this.height,
};
this.thumbs = [];
this.loadImages.forEach((img, i) => {
var nameEnum = {
0: { name: 'Ecocampus3', value: '/Ecocampus3' },
1: { name: 'Hoppin World', value: '/HoppinWorld' },
2: { name: 'Distrame', value: '/Distrame' },
3: { name: 'Club les Piranhas du Nord', value: '/CAPN' },
};
let texture = PIXI.Texture.from(img.img);
texture.title = nameEnum[i];
const sprite = new PIXI.Sprite(texture);
let container = new PIXI.Container();
let spriteContainer = new PIXI.Container();
let mask = new PIXI.Sprite(PIXI.Texture.WHITE);
mask.width = this.width;
mask.height = this.height;
sprite.mask = mask;
sprite.anchor.set(0.5);
sprite.position.set(sprite.texture.orig.width / 2, sprite.texture.orig.height / 2);
let image = {
w: sprite.texture.orig.width,
h: sprite.texture.orig.height,
};
let cover = fit(image, parent);
spriteContainer.position.set(cover.left, cover.top);
spriteContainer.scale.set(cover.scale, cover.scale);
container.x = (this.margin + this.width) * i;
container.y = this.height / 10;
spriteContainer.addChild(sprite);
container.interactive = true;
container.on('mouseover', this.mouseOn, { passive: true });
container.on('mouseout', this.mouseOut, { passive: true });
container.on('click', this.redirect, { passive: true });
container.on('touchstart', this.redirect, { passive: true });
container.on('touchmove', this.redirect, { passive: true });
container.addChild(spriteContainer);
container.addChild(mask);
this.container.addChild(container);
this.thumbs.push(container);
});
}
redirect(e) {
let e1 = e.currentTarget.children[0].children[0];
let e2 = e1.texture.title.value;
window.location.replace(e2);
}
mouseOut(e) {
let e1 = e.currentTarget.children[0].children[0];
gsap.to(e1.scale, {
duration: 1,
x: 1,
y: 1,
});
e1.children[0].text = '';
}
mouseOn(e) {
let e1 = e.target.children[0].children[0];
const skewStyle = new PIXI.TextStyle({
fontFamily: 'Raleway',
fontSize: '60px',
dropShadowColor: '#fff',
fill: '#fff',
fontWeight: 'bold',
});
let e2 = e1.texture.title.name;
const basicText1 = new PIXI.Text(e2, skewStyle);
basicText1.x = -400;
basicText1.y = 100;
gsap.to(e1.scale, {
duration: 1,
x: 1.1,
y: 1.1,
});
if (e1.children[0]) {
e1.children[0].text = e2;
} else {
e1.addChild(basicText1);
}
}
calcPos(scr, pos) {
let temp = ((scr + pos + this.WHOLEWIDTH + this.width + this.margin) % this.WHOLEWIDTH) - this.width - this.margin;
return temp;
}
render() {
this.app.ticker.add(() => {
this.app.renderer.render(this.container);
this.scroll -= (this.scroll - this.scrollTarget) * 0.1;
this.scrollTarget *= 0.9;
this.thumbs.forEach((th) => {
th.position.x = this.calcPos(this.scroll, th.position.x);
});
});
}
Thank you in advance :D

How to trigger createjs animation on slick slider afterchange callback?

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

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>

Lazy Loading a Repeating Iframe Div

I have a lazy-load code block here:
(function($){
var items = [];
function winPos(win) {
return { x: 0, y: 0, x2: win.width() - 1, y2: win.height() - 1 };
}
function pos(win, el) {
var p = el.offset();
var x = p.left - win.scrollLeft();
var y = p.top - win.scrollTop();
return { x: x, y: y, x2: x + el.width() -1, y2: y + el.height() - 1 };
}
function intersects(a, b) {
return !(a.x2 < b.x || a.x > b.x2 || a.y2 < b.y || a.y > b.y2);
}
function check(win, w, item) {
var p = pos(win, $(item.el));
var s = intersects(w, p);
if (s != item.shown) {
item.shown = s;
(s ? item.show : item.hide).call(item.el);
}
}
$.fn.visible = function(show, hide){
var win = $(window), w = winPos(win);
return this.each(function(i, el){
var item = { el: el, show: show, hide: hide, shown: false };
items.push(item);
check(win, w, item);
});
};
$(window).on('scroll resize', function(e){
var win = $(window), w = winPos(win);
for (var i = 0; i < items.length; i++) {
check(win, w, items[i]);
}
});
})(jQuery);
// Lazy loading images plugin
(function($){
$.fn.lazyImage = function(){
return this.visible(function(){
$(this).append($('<img>', {'src': $(this).data('src') }).css('opacity', 0).load(function(){
$(this).animate({ opacity: 1 });
}));
}, function(){
$(this).empty();
});
};
})(jQuery);
// Usage
$('div').lazyImage();
https://jsfiddle.net/Guffa/u7bcms27/
I want to lazy load each iframe div.
*
Here's my code, that gets links and titles from the Reddit API, and loads the videos into Iframes.
fetch('https://www.reddit.com/r/cleanupearth.json')
.then(res=>res.json())
.then(res=>res.data.children)
.then(res=>res.map(post=>({
// author: post.data.author,
link: post.data.url,
img: post.data.thumbnail,
title: post.data.title
})))
.then(res=>res.map(render))
.then(res=>console.log(res))
const app = document.querySelector('#app');
const render = post => {
const node = document.createElement('div');
node.innerHTML= `${post.title}`;
node.className= 'clip-title';
app.appendChild(node);
//node.style.fontSize = "50px";
var regExp = /^.*(youtu\.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
var url = post.link;
// var url = "https://www.youtube.com/watch?v=MPmKEi4xXMg";
var match = url.match(regExp);
var strippedURL = match[2];
//alert("strippedURL is " + strippedURL);
if (match && match[2].length == 11) {
console.log(match[2]);
} else {
//error
console.log('error');
}
var a = document.createElement('iframe');
// iframe.id = 'appiframe';
a.className = "clip-content"
a.src = "https://www.youtube.com/embed/" + strippedURL; //add your iframe path here
a.width = "100%";
a.height = "100%";
a.padding = "500px";
app.style.textAlign = "center";
document.querySelector('#app').appendChild(a);
}
*
Here's an fiddle of the two snippets together.
https://jsfiddle.net/p5tL6jvr/
The original snippet creates an empty array called items:
var items = [];
and loads images into an append function;
$(this).append($('<img>', {'src': $(this).data('src') }).css('opacity', 0).load(function()
I could load the entire id=#app div into the items array, and swap the img line for a line that creates iframes. What is the best way to approach this?
BTW, if anyone knows of a succinct way to do this in pure Javascript, instead of JQuery, that would be interesting to read.

Null Reference after restarting a State

I created a little game with Phaser for presentation purposes. After you've won or lost you can restart the game. This is done with states. When I try to fire a bullet after the game has been restarted, a null reference error occurs and the game freezes. It seems the null reference occurs because the this.game property is not set correctly in the Weapon classes after the state is restarted.
var PhaserGame = function () {
this.background = null;
this.stars = null;
this.player = null;
this.enemies = null;
this.cursors = null;
this.speed = 300;
this.weapons = [];
this.currentWeapon = 0;
this.weaponName = null;
this.score = 0;
};
PhaserGame.prototype = {
init: function () {
this.game.renderer.renderSession.roundPixels = true;
this.physics.startSystem(Phaser.Physics.ARCADE);
},
preload: function () {
this.game.time.advancedTiming = true;
},
create: function () {
this.background = this.add.tileSprite(0, 0, this.game.width, this.game.height, 'background');
this.background.autoScroll(-40, 0);
this.stars = this.add.tileSprite(0, 0, this.game.width, this.game.height, 'stars');
this.stars.autoScroll(-60, 0);
this.weapons.push(new Weapon.SingleBullet(this.game));
//this.weapons.push(new Weapon.FrontAndBack(this.game));
this.weapons.push(new Weapon.ThreeWay(this.game));
//this.weapons.push(new Weapon.EightWay(this.game));
this.weapons.push(new Weapon.ScatterShot(this.game));
this.weapons.push(new Weapon.Beam(this.game));
this.weapons.push(new Weapon.SplitShot(this.game));
//this.weapons.push(new Weapon.Pattern(this.game));
this.weapons.push(new Weapon.Rockets(this.game));
this.weapons.push(new Weapon.ScaleBullet(this.game));
//this.weapons.push(new Weapon.Combo1(this.game));
//this.weapons.push(new Weapon.Combo2(this.game));
this.currentWeapon = 0;
for (var i = 1; i < this.weapons.length; i++)
{
this.weapons[i].visible = false;
}
this.player = this.add.existing(new Spaceship(this.game, 100, 200, 'player'));
this.player.events.onKilled.add(this.toGameOver, this);
this.physics.arcade.enable(this.player);
this.player.body.collideWorldBounds = true;
this.player.animations.add('flame', [0, 1, 2, 3], 10, true);
this.player.animations.play('flame');
//Enemies
this.enemies = this.add.group();
//Enable Physics for Enemies
//this.physics.arcade.enable(this.enemies);
this.enemies.enableBody = true;
for (var i = 0; i < 24; i++) {
//create a star inside the group
var enemy = this.enemies.add(new Enemy(this.game, 1000 + (i * 50), 10 + Math.random() * 300, 'enemy'));
enemy.events.onKilled.add(this.raiseCounter, this);
}
//this.weaponName = this.add.bitmapText(8, 364, 'shmupfont', "ENTER = Next Weapon", 24);
// Cursor keys to fly + space to fire
this.cursors = this.input.keyboard.createCursorKeys();
this.input.keyboard.addKeyCapture([ Phaser.Keyboard.SPACEBAR ]);
var changeKey = this.input.keyboard.addKey(Phaser.Keyboard.ENTER);
changeKey.onDown.add(this.nextWeapon, this);
},
nextWeapon: function () {
// Tidy-up the current weapon
this.weapons[this.currentWeapon].visible = false;
this.weapons[this.currentWeapon].callAll('reset', null, 0, 0);
this.weapons[this.currentWeapon].setAll('exists', false);
// Activate the new one
this.currentWeapon++;
if (this.currentWeapon === this.weapons.length)
{
this.currentWeapon = 0;
}
this.weapons[this.currentWeapon].visible = true;
//this.weaponName.text = this.weapons[this.currentWeapon].name;
},
enemyHit: function (bullet, enemy) {
bullet.kill();
enemy.dealDamage(2);
},
playerHit: function (player, enemy) {
player.dealDamage(10);
enemy.dealDamage(1);
},
raiseCounter: function () {
this.score++;
},
toGameOver: function () {
this.game.state.start('GameOver', true, false, this.score);
},
update: function () {
//Framerate
this.game.debug.text(this.time.fps || '--', 2, 14, "#00ff00");
this.game.debug.text('Health: ' + this.player.health || 'Health: ---', 2, 30, "#00ff00");
this.game.debug.text('Counter: ' + this.score || 'Counter: ---', 2, 44, "#00ff00");
this.game.physics.arcade.overlap(this.weapons[this.currentWeapon], this.enemies, this.enemyHit, null, this);
this.game.physics.arcade.overlap(this.player, this.enemies, this.playerHit, null, this);
this.player.body.velocity.set(0);
this.enemies.setAll('body.velocity.x', -50);
if (this.cursors.left.isDown)
{
this.player.body.velocity.x = -this.speed;
}
else if (this.cursors.right.isDown)
{
this.player.body.velocity.x = this.speed;
}
if (this.cursors.up.isDown)
{
this.player.body.velocity.y = -this.speed;
}
else if (this.cursors.down.isDown)
{
this.player.body.velocity.y = this.speed;
}
if (this.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR))
{
this.weapons[this.currentWeapon].fire(this.player);
}
}
};
The weapon-classes were taken from Phaser-Coding-Tips 7:
Weapon.SingleBullet = function (game) {
console.log(game);
Phaser.Group.call(this, game, game.world, 'Single Bullet', false, true, Phaser.Physics.ARCADE);
this.nextFire = 0;
this.bulletSpeed = 600;
this.fireRate = 200;
for (var i = 0; i < 64; i++)
{
this.add(new Bullet(game, 'bullet5'), true);
}
return this;
};
Weapon.SingleBullet.prototype = Object.create(Phaser.Group.prototype);
Weapon.SingleBullet.prototype.constructor = Weapon.SingleBullet;
Weapon.SingleBullet.prototype.fire = function (source) {
//Here occurs the problem, because this.game is null after restarting the state
if (this.game.time.time < this.nextFire) { return; }
var x = source.x + 50;
var y = source.y + 15;
this.getFirstExists(false).fire(x, y, 0, this.bulletSpeed, 0, 0);
this.nextFire = this.game.time.time + this.fireRate;
};
The problem occurs consistent in all Weapon classes after restarting the state.
In the beginning of the create-method before weapons is filled, i forgot to empty the array. The funny thing is: I tried emptying the array before and it didn't work. When i logged the length of weapons it suddenly started to work as expected. Maybe the cause was a strange optimization made by the javascript-engine.

Categories

Resources