Visualization of audio(webaudio) not working in chrome - javascript

I want to visualize audio that is coming in from webrtc(JSSIP). I used WebAudio, connected analyzer node and it seems to be working fine with Firefox.
In chrome browser, thing seems to be not working. I can listen to the audio in Chrome but am not able to visualize it, it doesn't throw any error. I checked the array, it shows -Infinity.
What could be the reason for it? How can I visualize in chrome?
console.log(dataArray);
>> Float32Array(512) [-Infinity, -Infinity, -Infinity, -Infinity, -Infinity, -Infinity, -Infinity, …]
Code for the same
const AudioContext = window.AudioContext || window.webkitAudioContext;
var audioElement;
var audioCtx;
var analyser;
const canvas = document.getElementById("visualizer");
const canvasCtx = canvas.getContext("2d");
canvas.width = window.innerWidth - 50;
canvas.height = canvas.width / 2;
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var drawVisual;
const socketUrl = "wss://website.com:8089/ws";
var ua;
var configuration = {
sockets: [],
'uri': "",
'password': "",
'username': "",
'register': true
};
var room = "";
var session;
var callOptions = {
'mediaConstraints': { 'audio': true, 'video': false },
'pcConfig': {
'iceServers': [
{ 'urls': ['stun:stun.l.google.com:19302'] },
]
}
};
const callBtn = document.getElementById('call-btn');
const hangupBtn = document.getElementById('hangup-btn');
hangupBtn.setAttribute('disabled','disabled');
var initAudioElement = function () {
audioElement = new window.Audio();
audioElement.autoplay = true;
audioElement.crossOrigin = "anonymous";
document.body.appendChild(audioElement);
}
var audioCtxInit = function () {
try {
audioCtx = new AudioContext();
analyser = audioCtx.createAnalyser();
} catch (e) {
alert('Web audio not supported.');
}
var audioTrack = audioCtx.createMediaElementSource(audioElement);
audioTrack.connect(analyser);
analyser.connect(audioCtx.destination);
}
var initializeJsSIP = function () {
if (ua) {
ua.stop();
ua = null;
}
try {
const socket = new JsSIP.WebSocketInterface(socketUrl);
JsSIP.debug.disable('JsSIP:*'); // Debugger
configuration.sockets = [socket];
configuration.uri = "";
ua = new JsSIP.UA(configuration);
} catch (error) {
console.log(error);
}
ua.on("connecting", () => {
console.log('UA "connecting" event');
});
ua.on("connected", () => {
console.log('UA "connected" event');
});
ua.on("disconnected", () => {
console.log('UA "disconnected" event');
});
ua.on("registered", (data) => {
console.log('UA "registered" event', data);
});
ua.on("unregistered", () => {
console.log('UA "unregistered" event');
});
ua.on("registrationFailed", (data) => {
console.log('UA "registrationFailed" event', data);
});
ua.on("newRTCSession", ({ originator, session: rtcSession, request: rtcRequest }) => {
console.log('UA "newRTCSession" event');
// identify call direction
if (originator === "local") {
const foundUri = rtcRequest.to.toString();
const delimiterPosition = foundUri.indexOf(";") || null;
console.log(`foundUri: ${foundUri}`);
} else if (originator === "remote") {
const foundUri = rtcRequest.from.toString();
const delimiterPosition = foundUri.indexOf(";") || null;
console.log(`foundUri: ${foundUri}`);
}
if (session) { // hangup any existing call
session.terminate();
}
session = rtcSession;
session.on("failed", (data) => {
console.log('rtcSession "failed" event', data);
session = null;
});
session.on("ended", () => {
console.log('rtcSession "ended" event');
session = null;
});
session.on("accepted", () => {
console.log('rtcSession "accepted" event');
[
audioElement.srcObject,
] = session.connection.getRemoteStreams();
var playPromise = audioElement.play();
if (typeof playPromise !== "undefined") {
playPromise
.then(() => {
console.log("playing");
visualize();
})
.catch((error) => {
console.log(error);
});
}
});
});
ua.start();
}
function visualize() {
var WIDTH = canvas.width;
var HEIGHT = canvas.height;
analyser.fftSize = 2 ** 10;
var bufferLength = analyser.frequencyBinCount;
var dataArray = new Float32Array(bufferLength);
canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
function draw() {
drawVisual = requestAnimationFrame(draw);
analyser.getFloatFrequencyData(dataArray);
canvasCtx.fillStyle = 'rgb(0, 0, 0)';
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
var barWidth = (WIDTH / bufferLength) * 2.5;
var barHeight;
var x = 0;
for (var i = 0; i < bufferLength; i++) {
barHeight = (dataArray[i] + 140) * 2;
canvasCtx.fillStyle = 'rgb(' + Math.floor(barHeight + 100) + ',50,50)';
canvasCtx.fillRect(x, HEIGHT - barHeight / 2, barWidth, barHeight / 2);
x += barWidth + 1;
}
}
draw();
}
callBtn.addEventListener('click', function () {
callBtn.setAttribute('disabled','disabled');
hangupBtn.removeAttribute('disabled');
if (!audioCtx) {
audioCtxInit();
}
// check if context is in suspended state (autoplay policy)
if (audioCtx.state === 'suspended') {
audioCtx.resume();
}
ua.call(room, callOptions);
});
hangupBtn.addEventListener('click', function () {
callBtn.removeAttribute('disabled');
hangupBtn.setAttribute('disabled', 'disabled');
if (drawVisual) {
canvasCtx.clearRect(0, 0, canvas.width, canvas.height);
canvasCtx.fillStyle = 'rgb(0, 0, 0)';
canvasCtx.fillRect(0, 0, canvas.width, canvas.height);
window.cancelAnimationFrame(drawVisual);
drawVisual = null;
}
ua.terminateSessions();
});
window.onload = function () {
readyStateTimer = setInterval(function () {
if (document.readyState === "complete") {
clearInterval(readyStateTimer);
initAudioElement();
initializeJsSIP();
}
}, 500);
}
window.onbeforeunload = function () {
audioElement.parentNode.removeChild(this.audioElement);
delete audioElement;
if (ua) {
ua.stop();
ua = null;
}
};

Related

How to send data from Node.js(webpack) to pure Node.js(express)?

I am getting data in a local storage of Webpack in JSON format. Node.js of Webpack is not allowing me to create a connection with MySQL. So, I am thinking if there is a way to send data to a backend(pure Node/Express server) like REST API.
I cannot use MySQL directly in Webpack node.js file
1.ref stackoveflow
2.ref GitHub
Below is my Webpack code I want save my localstorage data to database like MySQL, mongoDB.
import twitter from 'twitter-text';
import PDFJSAnnotate from '../';
import initColorPicker from './shared/initColorPicker';
/*import mysql from '../';
var con = mysql.createConnection({
host: "localhost",
user: "ali",
password: "demopassword"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});*/
//var hummus = require('HummusJS/hummus');
const { UI } = PDFJSAnnotate;
const documentId = 'question.pdf';
let PAGE_HEIGHT;
let RENDER_OPTIONS = {
documentId,
pdfDocument: null,
scale: parseFloat(localStorage.getItem(`${documentId}/scale`), 10) || 1.33,
rotate: parseInt(localStorage.getItem(`${documentId}/rotate`), 10) || 0
};
PDFJSAnnotate.setStoreAdapter(new PDFJSAnnotate.LocalStoreAdapter());
PDFJS.workerSrc = './shared/pdf.worker.js';
//var annotationz = localStorage.getItem(RENDER_OPTIONS.documentId + '/annotations') || [];
//console.log(annotationz);
// Render stuff
let NUM_PAGES = 0;
document.getElementById('content-wrapper').addEventListener('scroll', function (e) {
let visiblePageNum = Math.round(e.target.scrollTop / PAGE_HEIGHT) + 1;
let visiblePage = document.querySelector(`.page[data-page-number="${visiblePageNum}"][data-loaded="false"]`);
if (visiblePage) {
setTimeout(function () {
UI.renderPage(visiblePageNum, RENDER_OPTIONS);
});
}
});
function render() {
PDFJS.getDocument(RENDER_OPTIONS.documentId).then((pdf) => {
RENDER_OPTIONS.pdfDocument = pdf;
let viewer = document.getElementById('viewer');
viewer.innerHTML = '';
NUM_PAGES = pdf.pdfInfo.numPages;
for (let i=0; i<NUM_PAGES; i++) {
let page = UI.createPage(i+1);
viewer.appendChild(page);
}
UI.renderPage(1, RENDER_OPTIONS).then(([pdfPage, annotations]) => {
let viewport = pdfPage.getViewport(RENDER_OPTIONS.scale, RENDER_OPTIONS.rotate);
PAGE_HEIGHT = viewport.height;
});
});
}
render();
// Text stuff
(function () {
let textSize;
let textColor;
// let fontface;
function initText() {
let size = document.querySelector('.toolbar .text-size');
[8, 9, 10, 11, 12, 14, 18, 24, 30, 36, 48, 60, 72, 96].forEach((s) => {
size.appendChild(new Option (s, s));
});
/*let face = document.querySelector('.toolbar .font-face');
['fontGeorgiaSerif', 'fontPalatinoSerif', 'fontTimesSerif', 'Sans-Serif Fonts', 'fontArialSansSerif', 'fontComicSansMS', 'fontVerdanaSansMS', 'Monospace Fonts', 'fontCourierNew', 'fontLucidaConsole'].forEach((s) => {
face.appendChild(new Option (s, s));
});*/
setText(
localStorage.getItem(`${RENDER_OPTIONS.documentId}/text/size`) || 10,
localStorage.getItem(`${RENDER_OPTIONS.documentId}/text/color`) || '#000000'
//localStorage.getItem(`${RENDER_OPTIONS.documentId}/text/face`) || 'fontGeorgiaSerif'
// console.log(${RENDER_OPTIONS.documentId});
);
initColorPicker(document.querySelector('.text-color'), textColor, function (value) {
setText(textSize, value);
});
}
function setText(size, color) {
let modified = false;
if (textSize !== size) {
modified = true;
textSize = size;
localStorage.setItem(`${RENDER_OPTIONS.documentId}/text/size`, textSize);
document.querySelector('.toolbar .text-size').value = textSize;
}
/* if (fontface !== face) {
modified = true;
fontface = face;
localStorage.setItem(`${RENDER_OPTIONS.documentId}/text/face`, fontface);
document.querySelector('.toolbar .font-face').value = fontface;
}*/
if (textColor !== color) {
modified = true;
textColor = color;
localStorage.setItem(`${RENDER_OPTIONS.documentId}/text/color`, textColor);
let selected = document.querySelector('.toolbar .text-color.color-selected');
if (selected) {
selected.classList.remove('color-selected');
selected.removeAttribute('aria-selected');
}
selected = document.querySelector(`.toolbar .text-color[data-color="${color}"]`);
if (selected) {
selected.classList.add('color-selected');
selected.setAttribute('aria-selected', true);
}
}
if (modified) {
UI.setText(textSize, textColor);
}
}
function handleTextSizeChange(e) {
setText(e.target.value, textColor);
}
document.querySelector('.toolbar .text-size').addEventListener('change', handleTextSizeChange);
initText();
})();
// Pen stuff
(function () {
let penSize;
let penColor;
function initPen() {
let size = document.querySelector('.toolbar .pen-size');
for (let i=0; i<20; i++) {
size.appendChild(new Option(i+1, i+1));
}
setPen(
localStorage.getItem(`${RENDER_OPTIONS.documentId}/pen/size`) || 1,
localStorage.getItem(`${RENDER_OPTIONS.documentId}/pen/color`) || '#000000'
);
initColorPicker(document.querySelector('.pen-color'), penColor, function (value) {
setPen(penSize, value);
});
}
function setPen(size, color) {
let modified = false;
if (penSize !== size) {
modified = true;
penSize = size;
localStorage.setItem(`${RENDER_OPTIONS.documentId}/pen/size`, penSize);
document.querySelector('.toolbar .pen-size').value = penSize;
}
if (penColor !== color) {
modified = true;
penColor = color;
localStorage.setItem(`${RENDER_OPTIONS.documentId}/pen/color`, penColor);
let selected = document.querySelector('.toolbar .pen-color.color-selected');
if (selected) {
selected.classList.remove('color-selected');
selected.removeAttribute('aria-selected');
}
selected = document.querySelector(`.toolbar .pen-color[data-color="${color}"]`);
if (selected) {
selected.classList.add('color-selected');
selected.setAttribute('aria-selected', true);
}
}
if (modified) {
UI.setPen(penSize, penColor);
}
}
function handlePenSizeChange(e) {
setPen(e.target.value, penColor);
}
document.querySelector('.toolbar .pen-size').addEventListener('change', handlePenSizeChange);
initPen();
})();
// Toolbar buttons
(function () {
let tooltype = localStorage.getItem(`${RENDER_OPTIONS.documentId}/tooltype`) || 'cursor';
if (tooltype) {
setActiveToolbarItem(tooltype, document.querySelector(`.toolbar button[data-tooltype=${tooltype}]`));
}
function setActiveToolbarItem(type, button) {
let active = document.querySelector('.toolbar button.active');
if (active) {
active.classList.remove('active');
switch (tooltype) {
case 'cursor':
UI.disableEdit();
break;
case 'draw':
UI.disablePen();
break;
case 'text':
UI.disableText();
break;
case 'point':
UI.disablePoint();
break;
case 'area':
case 'highlight':
case 'strikeout':
UI.disableRect();
break;
}
}
if (button) {
button.classList.add('active');
}
if (tooltype !== type) {
localStorage.setItem(`${RENDER_OPTIONS.documentId}/tooltype`, type);
}
tooltype = type;
switch (type) {
case 'cursor':
UI.enableEdit();
break;
case 'draw':
UI.enablePen();
break;
case 'text':
UI.enableText();
break;
case 'point':
UI.enablePoint();
break;
case 'area':
case 'highlight':
case 'strikeout':
UI.enableRect(type);
break;
}
}
function handleToolbarClick(e) {
if (e.target.nodeName === 'BUTTON') {
setActiveToolbarItem(e.target.getAttribute('data-tooltype'), e.target);
}
}
document.querySelector('.toolbar').addEventListener('click', handleToolbarClick);
})();
// Scale/rotate
(function () {
function setScaleRotate(scale, rotate) {
scale = parseFloat(scale, 10);
rotate = parseInt(rotate, 10);
if (RENDER_OPTIONS.scale !== scale || RENDER_OPTIONS.rotate !== rotate) {
RENDER_OPTIONS.scale = scale;
RENDER_OPTIONS.rotate = rotate;
localStorage.setItem(`${RENDER_OPTIONS.documentId}/scale`, RENDER_OPTIONS.scale);
localStorage.setItem(`${RENDER_OPTIONS.documentId}/rotate`, RENDER_OPTIONS.rotate % 360);
render();
}
}
function handleScaleChange(e) {
setScaleRotate(e.target.value, RENDER_OPTIONS.rotate);
}
function handleRotateCWClick() {
setScaleRotate(RENDER_OPTIONS.scale, RENDER_OPTIONS.rotate + 90);
}
function handleRotateCCWClick() {
setScaleRotate(RENDER_OPTIONS.scale, RENDER_OPTIONS.rotate - 90);
}
document.querySelector('.toolbar select.scale').value = RENDER_OPTIONS.scale;
document.querySelector('.toolbar select.scale').addEventListener('change', handleScaleChange);
document.querySelector('.toolbar .rotate-ccw').addEventListener('click', handleRotateCCWClick);
document.querySelector('.toolbar .rotate-cw').addEventListener('click', handleRotateCWClick);
})();
// Clear toolbar button
(function () {
function handleClearClick(e) {
if (confirm('Are you sure you want to clear annotations?')) {
for (let i=0; i<NUM_PAGES; i++) {
document.querySelector(`div#pageContainer${i+1} svg.annotationLayer`).innerHTML = '';
}
localStorage.removeItem(`${RENDER_OPTIONS.documentId}/annotations`);
}
}
document.querySelector('a.clear').addEventListener('click', handleClearClick);
})();
// Comment stuff
(function (window, document) {
let commentList = document.querySelector('#comment-wrapper .comment-list-container');
let commentForm = document.querySelector('#comment-wrapper .comment-list-form');
let commentText = commentForm.querySelector('input[type="text"]');
function supportsComments(target) {
let type = target.getAttribute('data-pdf-annotate-type');
return ['point', 'highlight', 'area'].indexOf(type) > -1;
}
function insertComment(comment) {
let child = document.createElement('div');
child.className = 'comment-list-item';
child.innerHTML = twitter.autoLink(twitter.htmlEscape(comment.content));
commentList.appendChild(child);
}
function handleAnnotationClick(target) {
if (supportsComments(target)) {
let documentId = target.parentNode.getAttribute('data-pdf-annotate-document');
let annotationId = target.getAttribute('data-pdf-annotate-id');
PDFJSAnnotate.getStoreAdapter().getComments(documentId, annotationId).then((comments) => {
commentList.innerHTML = '';
commentForm.style.display = '';
commentText.focus();
commentForm.onsubmit = function () {
PDFJSAnnotate.getStoreAdapter().addComment(documentId, annotationId, commentText.value.trim())
.then(insertComment)
.then(() => {
commentText.value = '';
commentText.focus();
});
return false;
};
comments.forEach(insertComment);
});
}
}
function handleAnnotationBlur(target) {
if (supportsComments(target)) {
commentList.innerHTML = '';
commentForm.style.display = 'none';
commentForm.onsubmit = null;
insertComment({content: 'No comments'});
}
}
UI.addEventListener('annotation:click', handleAnnotationClick);
UI.addEventListener('annotation:blur', handleAnnotationBlur);
})(window, document);
Simple AJAX was working on the page because Webpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging read more...
So in my case Node js was using Webpack module to load javascript in a browser. It is pure javascript. So I just implemented ajax on my javascript code and it is simply working like a REST API.

Uncaught Type error: is not a function

I am making a javascript game, using Canvas. It works well superficially, but "Uncaught TypeError: game_state.Update is not a function" keeps going. I cannot know the reason for all day...How can I solve the problem?
error image1, error image2
Suspected files are below.
gfw.js
function onGameInit()
{
document.title = "Lion Travel";
GAME_FPS = 30;
debugSystem.debugMode = true;
//resourcePreLoading
resourcePreLoader.AddImage("/.c9/img/title_background.png");
resourcePreLoader.AddImage("/.c9/img/title_start_off.png");
resourcePreLoader.AddImage("/.c9/img/title_start_on.png");
resourcePreLoader.AddImage("/.c9/img/title_ranking_off.png");
resourcePreLoader.AddImage("/.c9/img/title_ranking_on.png");
resourcePreLoader.AddImage("/.c9/img/game_background_sky.png");
soundSystem.AddSound("/.c9/background.mp3", 1);
after_loading_state = new TitleState();
game_state = TitleState;
setInterval(gameLoop, 1000 / GAME_FPS);
}
window.addEventListener("load", onGameInit, false);
GameFramework.js
window.addEventListener("mousedown", onMouseDown, false);
window.addEventListener("mouseup", onMouseUp, false);
var GAME_FPS;
var game_state;
function onMouseDown(e)
{
if(game_state.onMouseDown != undefined)
game_state.onMouseDown(e);
// alert("x:" + inputSystem.mouseX + " y:" + inputSystem.mouseY);
}
function onMouseUp(e)
{
if(game_state.onMouseUp != undefined)
game_state.onMouseUp(e);
}
function ChangeGameState(nextGameState)
{
if(nextGameState.Init == undefined)
return;
if(nextGameState.Update == undefined)
return;
if(nextGameState.Render == undefined)
return;
game_state = nextGameState;
game_state.Init();
}
function GameUpdate()
{
timerSystem.Update();
**game_state.Update();**
debugSystem.UseDebugMode();
}
function GameRender()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
game_state.Render();
if(debugSystem.debugMode)
{
Context.fillStyle = "#ffffff";
Context.font = '15px Arial';
Context.textBaseline = "top";
Context.fillText("fps: "+ frameCounter.Lastfps, 10, 10);
}
}
function gameLoop()
{
game_state = after_loading_state;
GameUpdate();
GameRender();
frameCounter.countFrame();
}
RS_Title.js
function TitleState()
{
this.imgBackground = resourcePreLoader.GetImage("/.c9/img/title_background.png");
this.imgButtonStartOff = resourcePreLoader.GetImage("/.c9/img/title_start_off.png");
this.imgButtonStartOn = resourcePreLoader.GetImage("/.c9/img/title_start_on.png");
this.imgButtonRankingOff = resourcePreLoader.GetImage("/.c9/img/title_ranking_off.png");
this.imgButtonRankingOn = resourcePreLoader.GetImage("/.c9/img/title_ranking_on.png");
soundSystem.PlayBackgroundMusic("/.c9/background.mp3");
return this;
}
TitleState.prototype.Init = function()
{
soundSystem.PlayBackgroundMusic("/.c9/background.mp3");
};
TitleState.prototype.Render = function()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
Context.drawImage(this.imgBackground, 0, 0);
//drawing button
if(inputSystem.mouseX > 170 && inputSystem.mouseX < 170+220
&& inputSystem.mouseY > 480 && inputSystem.mouseY < 480+100)
{
Context.drawImage(this.imgButtonStartOn, 170, 480);
this.flagButtonStart = true;
}
else
{
Context.drawImage(this.imgButtonStartOff, 170, 480);
this.flagButtonStart = false;
}
if(inputSystem.mouseX > 420 && inputSystem.mouseX < 420+220
&& inputSystem.mouseY > 480 && inputSystem.mouseY < 480+100)
{
Context.drawImage(this.imgButtonRankingOn, 420, 480);
this.flagButtonRanking = true;
}
else
{
Context.drawImage(this.imgButtonRankingOff, 420, 480);
this.flagButtonRanking = false;
}
};
TitleState.prototype.Update = function()
{
};
TitleState.prototype.onMouseDown = function()
{
if(this.flagButtonStart)
ChangeGameState(new PlayGameState());
after_loading_state = PlayGameState;
game_state = PlayGameState;
if(this.flagButtonRanking)
ChangeGameState();
};
RS_PlayGame.js
function PlayGameState()
{
this.imgBackgroundSky = resourcePreLoader.GetImage("/.c9/img/game_background_sky.png");
}
PlayGameState.prototype.Init = function()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
Context.drawImage(this.imgBackgroundSky, 0, 0);
};
PlayGameState.prototype.Render = function()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
Context.drawImage(this.imgBackgroundSky, 0, 0);
};
PlayGameState.prototype.Update = function()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
Context.drawImage(this.imgBackgroundSky, 0, 0);
};
As mentioned by the others, in the onMouseDown method you are assigning after_loading_state and game_state to PlayGameState which is a function and not an object. So later on when you want to access the Update method, it simply doesn't exist, because it is defined over the object prototype and not the function. You might want to do something like this so that you also avoid instantiating (calling) PlayGameState multiple times:
game_state = new PlayGameState();
ChangeGameState(game_state);
after_loading_state = game_state;

canvas is distorting itself and moving (fabric.js)

I just need an advice on where to look at or where to start as right now I am confused. Not sure if this is CSS issue, javascript, or fabric.js
Problem:
- I am adding a background image to canvas and sometimes it behaves really strange. And canvas is distorting itself sometimes on click, sometimes on resize, sometimes just without doing nothing. But this does not happen always.
These are two videos with the issue:
https://jumpshare.com/v/4FU3xWjqk4h6j0OwqaFs (this is just without
doing nothing).
https://jumpshare.com/v/tBS7NJC5VgccWnIssETw (this is me clicking on canvas)
This is how I add an image to canvas (fetching url via API):
$scope.openBlob = function($event, imageURL) {
$rootScope.isLoading();
$rootScope.centerSpinner();
if ($rootScope.currentTab === 1) {
var upload_thumb = angular.element($event.target.parentElement);
var circular = angular.element('<md-progress-circular md-mode="indeterminate" id="circular-images" md-diameter="30" ng-show="isAlsoLoading"></md-progress-circular>');
$compile(circular)($scope);
upload_thumb.prepend(circular);
} else {
var upload_thumb = angular.element($event.target.parentElement);
var circular = angular.element('<md-progress-circular md-mode="indeterminate" id="circular-new-middle" md-diameter="30" ng-show="isAlsoLoading"></md-progress-circular>');
$compile(circular)($scope);
upload_thumb.prepend(circular);
}
$rootScope.isAlsoLoading = true;
$http({
method: "GET",
url: imageURL.full,
responseType: "blob"
}).then(
function(res) {
var reader = new FileReader();
reader.readAsDataURL(res.data);
reader.onload = function(e) {
canvas.loadMainImage(e.target.result);
$rootScope.started = true;
$rootScope.uploaded = true;
$rootScope.changeStyling();
};
},
function(res) {
console.log("For some reasons it failed to open", res);
});
if ($rootScope.currentTab === 1) {
$rootScope.$on('editor.mainImage.loaded', function() {
$rootScope.isAlsoLoading = false;
upload_thumb.find("#circular-images").remove();
$rootScope.resetFilters();
$rootScope.isNotLoading();
});
} else {
$rootScope.$on('editor.mainImage.loaded', function() {
$rootScope.isAlsoLoading = false;
upload_thumb.find("#circular-new-middle").remove();
$rootScope.resetFilters();
$rootScope.isNotLoading();
});
}
}
LoadMainImage function content:
loadMainImage: function(url, height, width, dontFit, callback) {
var object;
fabric.util.loadImage(url, function(img) {
//img.crossOrigin = 'anonymous';
object = new fabric.Image(img, canvas.imageStatic);
object.name = 'mainImage';
if (width && height) {
object.width = width;
object.height = height;
}
canvas.mainImage = object;
canvas.fabric.forEachObject(function(obj) {
console.log('image object', obj);
if (obj && obj.name == 'mainImage') {
canvas.fabric.remove(obj);
}
});
canvas.fabric.add(object);
object.top = -0.5;
object.left = -0.5;
object.moveTo(0);
canvas.fabric.setHeight(object.height);
canvas.fabric.setWidth(object.width);
canvas.original.height = object.height;
canvas.original.width = object.width;
$rootScope.canvaswidth = canvas.original.width;
$rootScope.canvasheight = canvas.original.height;
$rootScope.calculateImageType(canvas.original.width, canvas.original.height);
if ($rootScope.gridadded) {
$rootScope.removeGrid();
$rootScope.addGrid();
}
if (!dontFit) {
canvas.fitToScreen();
}
$rootScope.$apply(function() {
$rootScope.$emit('editor.mainImage.loaded');
});
if (callback) {
callback();
}
});
},
Fit to screen function:
$scope.fitToScreen = function () {
$scope.zoom = canvas.currentZoom * 100;
if (canvas.mainImage) {
var oWidth = canvas.mainImage.width,
oHeight = canvas.mainImage.height;
} else {
var oWidth = canvas.original.width,
oHeight = canvas.original.height;
}
var maxScale = Math.min(3582 / oHeight, 5731 / oWidth) * 100,
minScale = Math.min(141 / oHeight, 211 / oWidth) * 100;
$scope.maxScale = Math.ceil(maxScale);
$scope.minScale = Math.ceil(minScale);
canvas.zoom(canvas.currentZoom);
};
UPDATE: I am assuming that it might be scaling (zooming in and zooming out issue)

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.

Categories

Resources