Pixi JS 7 / Error on PIXI.Assets.load(json) - 2d

i take this code from Pixi examples ( https://pixijs.io/examples/?v=dev#/sprite/animatedsprite-jet.js ) :
import * as PIXI from 'pixi.js';
import json from './assets/fighter.json';
const app = new PIXI.Application({ background: '#1099bb' });
document.body.appendChild(app.view);
PIXI.Assets.load(json).then(() => {
// create an array of textures from an image path
const frames = [];
for (let i = 0; i < 30; i++) {
const val = i < 10 ? `0${i}` : i;
// magically works since the spritesheet was loaded with the pixi loader
frames.push(PIXI.Texture.from(`rollSequence00${val}.png`));
}
// create an AnimatedSprite (brings back memories from the days of Flash, right ?)
const anim = new PIXI.AnimatedSprite(frames);
/*
* An AnimatedSprite inherits all the properties of a PIXI sprite
* so you can change its position, its anchor, mask it, etc
*/
anim.x = app.screen.width / 2;
anim.y = app.screen.height / 2;
anim.anchor.set(0.5);
anim.animationSpeed = 0.5;
anim.play();
app.stage.addChild(anim);
// Animate the rotation
app.ticker.add(() => {
anim.rotation += 0.01;
});
});
And in browser console i'm get this message :
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'split')
at Resolver.ts:334:60
at Array.map (<anonymous>)
at Resolver.add (Resolver.ts:301:51)
at Assets.ts:407:35
at Array.map (<anonymous>)
at AssetsClass.load (Assets.ts:403:14)
I'm using a Vite(4.0)
I try using path to JSON in PIXI.Assets.load('/assets/fighter.json), is not help me.
But i'm get another message in browser console :
Uncaught (in promise) Error: [Loader.load] Failed to load http://localhost:5173/assets/fighter.json.
SyntaxError: Unexpected end of JSON input (at Loader.ts:151:27)
at Loader.ts:151:27
at async Promise.all (:5173/index 0)
at async Loader.load (Loader.ts:156:15)
at async AssetsClass._mapLoadToResolve (Assets.ts:672:30)
at async AssetsClass.load (Assets.ts:419:40)

Related

Typescript transformer, `node.parent` is undefined

I'm currently using a typescript transformer api, and I found that the node.parent is undefined.
My code is:
const transformerFactory: ts.TransformerFactory<ts.Node> = (
context: ts.TransformationContext
) => {
return (rootNode) => {
function visit(node: ts.Node): ts.Node {
node = ts.visitEachChild(node, visit, context);
// HERE node.parent IS UNDEFINED !
return filterFn(node, context);
}
return ts.visitNode(rootNode, visit);
};
};
const transformationResult = ts.transform(
sourceFile, [transformerFactory]
);
How can I find the parent of the node?
You can parse specifying to set the parent nodes:
const sourceFile = ts.createSourceFile(
"fileName.ts",
"class Test {}",
ts.ScriptTarget.Latest,
/* setParentNodes */ true, // specify this as true
);
Or do some operation on the node to get it to set its parent nodes (ex. type check the program... IIRC during binding it ensures the parent nodes are set).
Update based on comment
If you are creating these from a program, then you can do the following:
const options: ts.CompilerOptions = { allowJs: true };
const compilerHost = ts.createCompilerHost(options, /* setParentNodes */ true);
const program = ts.createProgram([this.filePath], options, compilerHost);

Starting Here.js Creating new MapView Get TypeError

I am trying to use harp.gl and used following tutorial.
tutorial:https://developer.here.com/tutorials/harpgl/
But I am getting following errors.
MapView.ts:919 Uncaught TypeError: Cannot read property 'addEventListener' of null
at new MapView (MapView.ts:919)
at JavaScript.js:2
You tried to use the method 2 of tutorial on https://developer.here.com/tutorials/harpgl/
I made the same followed tutorial method2 and into the file index.ts implemented the mapView.addEventListener as you can see what contains my index.ts below:
/*
* Copyright (C) 2017-2019 HERE Europe B.V.
* Licensed under Apache 2.0, see full license in LICENSE
* SPDX-License-Identifier: Apache-2.0
*/
import { GeoCoordinates } from "#here/harp-geoutils";
import { View } from "./View";
import { MapViewEventNames } from "#here/harp-mapview";
const app = new View({
canvas: document.getElementById("map") as HTMLCanvasElement
});
const mapView = app.mapView;
const options = { tilt: 45, distance: 3000 };
const coordinates = new GeoCoordinates(1.278676, 103.850216);
let azimuth = 300;
mapView.addEventListener(MapViewEventNames.Render, () => {
mapView.lookAt(coordinates, options.distance, options.tilt, (azimuth += 0.1))
});
mapView.beginAnimation();
// make map full-screen
mapView.resize(window.innerWidth, window.innerHeight);
// react on resize events from the browser.
window.addEventListener("resize", () => {
mapView.resize(window.innerWidth, window.innerHeight);
});
// center the camera to New York
mapView.lookAt(new GeoCoordinates(40.70398928, -74.01319808), 1500, 40, 0);
// make sure the map is rendered
mapView.update();
This code and mapView.addEventListener works for me properly without any errors.
Please check your hardware, Operation System, browser version.
Please test all examples on http://harp.gl.s3-website-us-east-1.amazonaws.com/docs/master/examples/ on your device and others.

Google Maps API complaining in IE11 about polyfill Array.from()

I'm trying to figure out an issue with Google Maps v3 and a polyfill we use for non-ES6 browsers (IE11 for example). The error we get is:
This site overrides Array.from() with an implementation that doesn't support iterables, which could cause Google Maps JavaScript API v3 to not work correctly.
The polyfill is: ( from https://vanillajstoolkit.com/polyfills/arrayfrom/ )
if (!Array.from) {
Array.from = (function () {
var toStr = Object.prototype.toString;
var isCallable = function (fn) {
return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
};
var toInteger = function (value) {
var number = Number(value);
if (isNaN(number)) { return 0; }
if (number === 0 || !isFinite(number)) { return number; }
return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
};
var maxSafeInteger = Math.pow(2, 53) - 1;
var toLength = function (value) {
var len = toInteger(value);
return Math.min(Math.max(len, 0), maxSafeInteger);
};
// The length property of the from method is 1.
return function from(arrayLike/*, mapFn, thisArg */) {
// 1. Let C be the this value.
var C = this;
// 2. Let items be ToObject(arrayLike).
var items = Object(arrayLike);
// 3. ReturnIfAbrupt(items).
if (arrayLike == null) {
throw new TypeError('Array.from requires an array-like object - not null or undefined');
}
// 4. If mapfn is undefined, then let mapping be false.
var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
var T;
if (typeof mapFn !== 'undefined') {
// 5. else
// 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
if (!isCallable(mapFn)) {
throw new TypeError('Array.from: when provided, the second argument must be a function');
}
// 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (arguments.length > 2) {
T = arguments[2];
}
}
// 10. Let lenValue be Get(items, "length").
// 11. Let len be ToLength(lenValue).
var len = toLength(items.length);
// 13. If IsConstructor(C) is true, then
// 13. a. Let A be the result of calling the [[Construct]] internal method
// of C with an argument list containing the single item len.
// 14. a. Else, Let A be ArrayCreate(len).
var A = isCallable(C) ? Object(new C(len)) : new Array(len);
// 16. Let k be 0.
var k = 0;
// 17. Repeat, while k < len… (also steps a - h)
var kValue;
while (k < len) {
kValue = items[k];
if (mapFn) {
A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
} else {
A[k] = kValue;
}
k += 1;
}
// 18. Let putStatus be Put(A, "length", len, true).
A.length = len;
// 20. Return A.
return A;
};
}());
}
This works fine on other pages - but for some reason Google Maps seems to have an issue with it!
Even more frustratingly, is that it then breaks one of my other plugins (a lazy load script), which works fine until the Google map stuff is loaded
Any ideas on what its moaning about, and how to fix it?
If you have IE11 or a VM, you can test it at: https://www.chambresdhotes.org/Detailed/1768.html (click on the map at the bottom of the page, and this will load the Google Map - but then you get this annoying error, and it breaks the lazyload scrolling after)
Thanks!

Here Maps - Datalens API - Updating Positions throwing Invalid Argument ERROR

Here Datalens API thown an Error when attempted to update Markers Positions. It's not everytime, but always occurs when wait some minutes(interactions).
ERROR:
message: "H.geo.Point (Argument #0 NaN)"
stack: "Error
at new C (https://js.api.here.com/v3/3.0/mapsjs-core.js:11:460)
at Wb (https://js.api.here.com/v3/3.0/mapsjs-core.js:14:180)
at new gc (https://js.api.here.com/v3/3.0/mapsjs-core.js:18:532)
at Object.s [as interp] (https://js.cit.datalens.api.here.com/latest/mapsjs-datalens.js:7:137026)
at a.step_ (https://js.cit.datalens.api.here.com/latest/mapsjs-datalens.js:7:135785)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2743:31)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (http://localhost:4200/polyfills.js:2510:47)
at push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask (http://localhost:4200/polyfills.js:2818:34)
at ZoneTask.invoke (http://localhost:4200/polyfills.js:2807:48)
at timer (http://localhost:4200/polyfills.js:4376:29)"
name: "InvalidArgumentError"
at: "InvalidArgumentError
at https://js.api.here.com/v3/3.0/mapsjs-core.js:11:521
at https://js.api.here.com/v3/3.0/mapsjs-core.js:320:26"
I checked ALL lat/lng combinations that i've pushed to data array, and there isn't invalid numbers.
try {
const data = [];
pos.docs.map((item, i) => {
const _lat = parseFloat(item.gps_latitude);
const _lng = parseFloat(item.gps_longitude);
if (!isNaN(_lat) && !isNaN(_lng) && !isNaN(item.gps_direction) && (_lat >= -90 && _lat <= 90) && (_lng >= -180 && _lng <= 180)) {
data.push([item.name, _lat, _lng]);
}
});
if (this.dataLensProvider) {
try {
this.dataLensProvider.setData({
columns: ['id', 'lat', 'lng'],
rows: data
});
} catch (e) {
console.log(e);
}
}
} catch (e) {
console.log(e);
}
Expected: All marker animations working.
Actual: after some updates the API returns ERROR and don't apply the changes.
This can have different reasons. Within the snippet above I could just guessing. Does the complete Array run through or stop at a specific position? Did you try to debug this part further?

Asynchronous update of nodes properties after the graph is rendered (Vivagraph.js)

I am trying to populate nodes' data in a graph, asynchronously.
How to ensure that data fetched asyncrosly is actually bound to the graph, and rendered when ready?
First, you render the graph structure, node and links.
Second, you render data as nodes' properties, when data is ready.
New node can by dynamically added by interacting on parents' nodes, and don't want to wait for completion of node's properties.
Please note I am using Vivagraph.js library.graph is an object created with the library, addLinks() and getNode() are its function properties - see the demo at Vivagraph demo, I am using that as a draft of my attempts.
The issue I experience is that nodes are rendered in the graph as soon as they are added - addNode() either addLinks(node1, node2) functions -, while node's properties fetched asynchronously - getNode(node).property = updatedValue - result undefined.
EDITED - Simplified code based on comment
Below I include a working mockup version, based on tutorial provided by #Anvaka, the author of this (awesome) library.
My goal is to render the graph immediately, enabling interaction, and update data while it is being fetched from third parties.
// attempt 1: fetch data async
var fetchInfo = function (graph, nodeId) {
var root = 'http://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/photos/' + nodeId,
method: 'GET'
}).then(function (data) {
graph.getNode(nodeId).data = data.thumbnailUrl;
console.log(graph.getNode(nodeId));
});
};
// attempt 2: defer ajax directly
var fetchInfo_2 = function (graph, nodeId) {
var root = 'http://jsonplaceholder.typicode.com';
return $.ajax({
url: root + '/photos/' + nodeId,
method: 'GET'
});
};
function main() {
// As in previous steps, we create a basic structure of a graph:
var graph = Viva.Graph.graph();
graph.addLink(1, 2);
fetchInfo(graph, 1); // updated data is undefined when graph is rendered
fetchInfo(graph, 2); // updated data is undefined when graph is rendered
/* trying a different outcome by deferring whole ajax
graph.getNode(1).data = fetchInfo_2(1).done(function(data) {
data.thumbnailUrl;
}); // the whole object is deferred but cannot fetch data
graph.getNode(2).data = fetchInfo_2(2).done(function(data) {
data.thumbnailUrl;
}); // the whole object is deferred but cannot fetch data
*/
var graphics = Viva.Graph.View.svgGraphics(),
nodeSize = 24,
addRelatedNodes = function (nodeId, isOn) {
for (var i = 0; i < 6; ++i) {
var child = Math.floor((Math.random() * 150) + nodeId);
// I add children and update data from external sources
graph.addLink(nodeId, child);
fetchInfo(graph, child);
}
};
// dynamically add nodes on mouse interaction
graphics.node(function (node) {
var ui = Viva.Graph.svg('image')
.attr('width', nodeSize)
.attr('height', nodeSize)
.link(node.data);
console.log('rendered', node.id, node.data);
$(ui).hover(function () {
// nodes are rendered; nodes' data is undefined
addRelatedNodes(node.id);
});
return ui;
}).placeNode(function (nodeUI, pos) {
nodeUI.attr('x', pos.x - nodeSize / 2).attr('y', pos.y - nodeSize / 2);
});
graphics.link(function (link) {
return Viva.Graph.svg('path')
.attr('stroke', 'gray');
}).placeLink(function (linkUI, fromPos, toPos) {
var data = 'M' + fromPos.x + ',' + fromPos.y +
'L' + toPos.x + ',' + toPos.y;
linkUI.attr("d", data);
})
var renderer = Viva.Graph.View.renderer(graph, {
graphics: graphics
});
renderer.run();
}
main();
svg {
width: 100%;
height: 100%;
}
<script src="https://rawgit.com/anvaka/VivaGraphJS/master/dist/vivagraph.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
As I said in the comments, any work you want to do as a result of an asynchronous process must be done in the callback. This includes any rendering work.
For jQuery's deferreds (like the result of an Ajax call), the callback is defined through .then or .done, enabling you to detach the act of fetching a resource from working with that resource.
Setting the image source is rendering work, so you must do it in the callback. Below is a function that fetches images and returns the deferred result and the node callback function uses that to do its own piece of work.
function fetchInfo(id) {
var root = 'http://jsonplaceholder.typicode.com';
return $.getJSON(root + '/photos/' + id);
}
function main() {
var graph = Viva.Graph.graph(),
graphics = Viva.Graph.View.svgGraphics(),
nodeSize = 24,
addRelatedNodes = function (nodeId, count) {
var childId, i;
for (i = 0; i < count; ++i) {
childId = Math.floor(Math.random() * 150) + nodeId;
graph.addLink(nodeId, childId);
}
};
graphics
.node(function (node) {
var ui = Viva.Graph.svg('image')
.attr('width', nodeSize)
.attr('height', nodeSize)
.link('http://www.ajaxload.info/images/exemples/24.gif');
$(ui).dblclick(function () {
addRelatedNodes(node.id, 6);
});
// render when ready
fetchInfo(node.id).done(function (data) {
ui.link(data.thumbnailUrl);
});
return ui;
})
.placeNode(function (nodeUI, pos) {
nodeUI.attr('x', pos.x - nodeSize / 2).attr('y', pos.y - nodeSize / 2);
})
.link(function (link) {
return Viva.Graph.svg('path')
.attr('stroke', 'gray');
})
.placeLink(function (linkUI, fromPos, toPos) {
var data =
'M' + fromPos.x + ',' + fromPos.y +
'L' + toPos.x + ',' + toPos.y;
linkUI.attr("d", data);
});
graph.addLink(1, 2);
Viva.Graph.View.renderer(graph, {
graphics: graphics
}).run();
}
main();
svg {
width: 100%;
height: 100%;
}
img {
cursor: pointer;
}
<script src="https://rawgit.com/anvaka/VivaGraphJS/master/dist/vivagraph.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
Sadly, it does not seem to run in the StackSnippets, but it works over on jsFiddle: http://jsfiddle.net/tL9992ua/

Resources