Angular html 5 Audio mute in last Chrome and without spectrum - angularjs

I have audio player directive, but in Chrome (and firefox) music mute in player and no draw spectrum. But in Opera and IE also its ok.
Help me find a Chrome (and firefox) bug...I think, i incorrect paste audio source in html.
var app = angular.module('app', []);
app.directive('spectrum', ['$document', '$timeout', function($document, $timeout) {
return function(scope, element, attr) {
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
var audioVisual = document.getElementById('player');
//console.log(wrap);
// canvas stuff
var canvas = document.getElementById('c');
canvas_context = canvas.getContext('2d');
var gradient = canvas_context.createLinearGradient(0, 0, 0, canvas.height);
gradient.addColorStop(1, '#550000');
gradient.addColorStop(0.75, '#ff0000');
gradient.addColorStop(0.25, '#ffff00');
gradient.addColorStop(0, '#ffff00');
canvas_context.fillStyle = gradient;
// audio stuff
audio = new Audio();
var audioSrc = 'http://www.noiseaddicts.com/samples/273.mp3';
//audio.__proto__ = scope.audio;
audio.src = audioSrc;
audio.controls = true;
audio.autoplay = true;
//scope.audios.paused = true;
audio.id = 'audioplayer';
audioVisual.appendChild(audio);
scope.audiosrc = audio.src;
// analyser stuff
var context = new AudioContext();
var analyser = context.createAnalyser();
analyser.fftSize = 2048;
// connect the stuff up to eachother/*
var source = context.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(context.destination);
freqAnalyser();
// draw the analyser to the canvas
function freqAnalyser() {
window.requestAnimFrame(freqAnalyser);
var sum;
var average;
var bar_width;
var scaled_average;
var num_bars = 60;
var data = new Uint8Array(128);
analyser.getByteFrequencyData(data);
// clear canvas
canvas_context.clearRect(0, 0, canvas.width, canvas.height);
var bin_size = Math.floor(data.length / num_bars);
for (var i = 0; i < num_bars; i += 1) {
sum = 0;
for (var j = 0; j < bin_size; j += 1) {
sum += data[(i * bin_size) + j];
}
average = sum / bin_size;
bar_width = canvas.width / num_bars;
scaled_average = (average / 256) * canvas.height;
canvas_context.fillRect(i * bar_width, canvas.height, bar_width - 2, - scaled_average);
}
}
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div spectrum>
<div class="spectrum">
<canvas id="c" width="500" height="200"></canvas>
</div>
<div id="player"><div id="audio-visual">
</div>
</div>
</div>

Related

Contour line data to DEM data

I was just wondering if there was a way to use the free ordnance survey contour line data and generate DEM data using it. I’ve seen plenty of people converting DEM data to contour line data but not the other way around, could anyone help me out here?
I would also add more relevant tags to this question, though I do not have the reputation, nor do the tags exist
OS Terrain 50 is available as ASCII grid as well as contours. This OpenLayers example reads the unzipped ASCII files directly to produce a single zoom level EPSG:27700 tiled DEM (using the Mapbox RGB encoding method), but you could use similar logic in VB to create and save a PNG tile grid.
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v6.5.0/css/ol.css" type="text/css">
<style>
html, body, .map {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
.map {
width: 100%;
height: calc(100% - 20px);
}
</style>
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v6.5.0/build/ol.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.6.0/proj4.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<div>
<label>
Elevation
<span id="info">0.0</span> meters
</label>
</div>
<script type="text/javascript">
proj4.defs('EPSG:27700', '+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +datum=OSGB36 +units=m +no_defs ');
ol.proj.proj4.register(proj4);
var canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 200;
var ctx = canvas.getContext('2d');
var imgData = ctx.createImageData(200, 200);
var layer = new ol.layer.Tile({
source: new ol.source.XYZ({
projection: 'EPSG:27700',
tileGrid: new ol.tilegrid.TileGrid({
tileSize: 200,
resolutions: [50],
extent: [0, 0, 700000, 1300000],
origin: [0, 0]
}),
crossOrigin: '',
imageSmoothing: false,
tileUrlFunction: function (tileCoord, pixelRatio, projection) {
var bounds = this.getTileGrid().getTileCoordExtent(tileCoord);
var x = (Math.round(bounds[0]/10)/10) + 10000;
var y = (Math.round(bounds[1]/10)/10) + 5000;
var a1y = (4 - (Math.floor(y/5000)%5))*5;
var a2y = (4 - (Math.floor(y/1000)%5))*5;
var y1 = Math.floor(y/100)%10;
a1y += (Math.floor(x/5000)%5);
a2y += (Math.floor(x/1000)%5);
var x1 = Math.floor(x/100)%10;
var tile500km = String.fromCharCode(a1y + Math.floor((a1y+17)/25) + "A".charCodeAt(0));
var tile100km = tile500km + String.fromCharCode(a2y + Math.floor((a2y+17)/25) + "A".charCodeAt(0));
var tile10km = tile100km + x1 + y1;
return 'https://mikenunn.net/data/terr50/grid/' + tile100km.toLowerCase() + '/' + tile10km + '.asc';
},
tileLoadFunction: function(tile, src) {
var xhr = new XMLHttpRequest();
xhr.addEventListener('loadend', function (evt) {
var data = this.response;
if (data !== undefined) {
var rows = data.split('\n');
if (rows.length >= 205) {
for (var j = 0; j < 200; j++) {
var values = rows[j + 5].split(' ');
for (var i = 0; i < 200; i++) {
var pixel = (parseFloat(values[i]) * 10) + 100000;
var index = (j * 200 + i) * 4;
imgData.data[index] = (pixel >> 16) & 0xFF;
imgData.data[index+1] = (pixel >> 8) & 0xFF;
imgData.data[index+2] = (pixel >> 0) & 0xFF;
imgData.data[index+3] = 0xFF;
}
}
ctx.putImageData(imgData, 0, 0);
tile.getImage().src = canvas.toDataURL();
}
} else {
tile.setState(3);
}
});
xhr.addEventListener('error', function () {
tile.setState(3);
});
xhr.open('GET', src);
xhr.send();
}
})
});
var map = new ol.Map({
target: 'map',
layers: [layer],
view: new ol.View({
projection: 'EPSG:27700',
center: ol.proj.fromLonLat([0, 51.5], 'EPSG:27700'),
zoom: 14
})
});
var showElevations = function(evt) {
if (evt.dragging) {
return;
}
map.forEachLayerAtPixel(
evt.pixel,
function(layer, pixel) {
var height = -10000 + (pixel[0] * 256 * 256 + pixel[1] * 256 + pixel[2]) * 0.1;
info.innerHTML = height.toFixed(1);
},
{
layerFilter: function(candidate) {
return layer === candidate;
}
}
);
};
map.on('pointermove', showElevations);
</script>
</body>
</html>

How to dynamically use object property as width in AngularJS (in ng-repeat)?

I cannot get the object's property to be read in ng-style(shape.radius || shape.length). I can't even get 1 to work at the moment, but would like to have an or statement included. Similar to my ng-class.
There is a button to generate shapes, and the shapes were created with a random size. Here is my code:
html:
<div ng-controller='ShapeController as sc'>
<div>
<p><input type="submit" value="Generate Random Shapes" ng-click="sc.generateShapes()"/></p>
<div ng-repeat="shape in sc.shapes">
<div class="shape" ng-class="{circle: shape.radius, square: shape.length}" ng-style="{'width': shape.length}"></div>
</div>
</div>
</div>
script:
var app = angular.module('app', []);
app.controller('ShapeController', function(){
var vm = this;
vm.shapes = [];
vm.randomShapes = [];
vm.width = 30;
function createCircle(radius) {
let circle = new Circle(radius);
vm.shapes.push(circle);
} // end createCircle
function createSquare(length) {
let square = new Square(length);
vm.shapes.push(square);
} // end createSquare
vm.generateShapes = function() {
let times = 50
for (let i = 0; i < times; i++) {
createCircle(getRandomNumber());
}
for (let i = 0; i < times; i++) {
createSquare(getRandomNumber());
}
sort(vm.shapes);
console.log(vm.shapes);
}; // end generateShapes
}); // end controller
function sort(arr) {
arr.sort(function(a,b){
return b.getArea() - a.getArea();
});
} // end sort function
function getRandomNumber() {
return Math.random() * (100-1) + 1;
}
width should be either in px(some unit like em, pt, etc) or %
ng-style="{'width': shape.length + 'px'}"

AngularJs lazyload fadeIn effect

app.controller('reviewCtrl',function($scope,$http) {
$http.get('http://~~~~~~~~~~~~~')
.success(function(data) {
$scope.reviewInfoList = data;
var cnt = 5;
var ind = 0;
$scope.reviewInfo = $scope.reviewInfoList.slice(0,cnt);
$scope.resetList = function(){
ind = 0
$scope.reviewInfo = $scope.reviewInfoList.slice(0,cnt);
};
$scope.loadMore = function() {
ind = ind + cnt
var r = cnt
if (ind + cnt > $scope.reviewInfoList.length) {
r = $scope.reviewInfoList.length - ind
}
$scope.reviewInfo = $scope.reviewInfo.concat($scope.reviewInfoList.slice(ind, r + ind))
}
});
This code is use in My project AngularJS.
I want add fadeIn effect at loadmore function
How to do that
some body help..please
You need to include the ng-animate script, and then when you create your module, include ngAnimate as a dependency. Then the rest is just css. Take a look at this snippet to see it in action.
angular.module('app', ['ngAnimate']).controller('reviewCtrl', function($scope, $http) {
$scope.reviewInfoList = [];
$scope.reviewInfo = [];
var cnt = 2;
var ind = 0;
//for the sake of this demo, generate some dummy data
for (var i = 0; i < 1000; i++) {
$scope.reviewInfoList.push(i);
}
$scope.loadMore = function() {
ind = ind + cnt
var r = cnt
if (ind + cnt > $scope.reviewInfoList.length) {
r = $scope.reviewInfoList.length - ind
}
$scope.reviewInfo = $scope.reviewInfo.concat($scope.reviewInfoList.slice(ind, r + ind))
}
//load the first bit right away
$scope.reviewInfo = $scope.reviewInfoList.slice(0, cnt);
$scope.resetList = function() {
ind = 0
$scope.reviewInfo = $scope.reviewInfoList.slice(0, cnt);
};
});
/* The starting CSS styles for the enter animation */
.fade.ng-enter {
transition: 0.5s linear all;
opacity: 0;
}
/* The finishing CSS styles for the enter animation */
.fade.ng-enter.ng-enter-active {
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular-animate.min.js"></script>
<div ng-app="app" ng-controller="reviewCtrl">
<button ng-click="loadMore()">Load more</button>
<ul>
<li class="fade" ng-repeat="review in reviewInfo">{{review}}</li>
</ul>
</div>

Meaning of hyphen in Angular tags

I found a bit of code on Plunker which I don't understand. It's a word cloud where the cloud is added to the page with:
<tang-cloud words="words" on-click="test(word)" width="500" height="500"></tang-cloud>
This is some how picked up by Angular. What I don't understand is I can find no references to "tang-cloud" in the rest of the code. Various "tangcloud" but nothing with a hyphen.
I'm totally new to Angular, I've stumbled across another case where this seems to happen, but all the tutorial cases I've seen would have used "tangcloud". If I remove the hyphen it stops working, so I must just be missing something simple.
Thank you
It's a directive. Since HTML is case-insensitive, angular converts the tangCloud directive to tang-cloud to be readable by HTML.
The tangCloud directive in tangCloud.js is where you'll find the code for that.
Edit: Just to follow up, you see the bit that says restrict: 'E'? That tells angular that you can use the directive as a custom element. When you make a directive camelcase, like tangCloud, angular will automatically convert it to tang-cloud.
.directive('tangCloud', ['$interpolate', '$compile', '$timeout', function ($interpolate, $compile, $timeout) {
var directive = {
restrict: 'E',
scope: {
width: '=',
height: '=',
words: '=',
onClick: '&',
spin: '='
},
template: function (tElement, tAttrs) {
var isClickable = angular.isDefined(tAttrs.onClick);
var clickAttr = isClickable ? 'ng-click="onClick({word : entry.word, id : entry.id})"' : '';
return "<div class='tangcloud'>" +
"<span ng-repeat='entry in words'" + clickAttr + ">{{entry.word}}</span>" +
"</div>";
},
compile: function (elem) {
elem.children().children()
.addClass('tangcloud-item-' + $interpolate.startSymbol() + 'entry.size' + $interpolate.endSymbol())
.addClass('tangcloud-item-hidden');
return function (scope, elem) {
var centerX = scope.width / 2;
var centerY = scope.height / 2;
var outOfBoundsCount = 0;
var takenSpots = [];
if (scope.words) {
scope.words = shuffleWords(scope.words);
determineWordPositions();
}
function shuffleWords(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function determineWordPositions() {
$timeout(function () {
var trendSpans = elem.children().eq(0).children();
var length = trendSpans.length;
for (var i = 0; i < length; i++) {
setWordSpanPosition(trendSpans.eq(i));
}
});
}
function setWordSpanPosition(span) {
var height = parseInt(window.getComputedStyle(span[0]).lineHeight, 10);
var width = span[0].offsetWidth;
var spot = setupDefaultSpot(width, height);
var angleMultiplier = 0;
while (spotNotUsable(spot) && outOfBoundsCount < 50) {
spot = moveSpotOnSpiral(spot, angleMultiplier);
angleMultiplier += 1;
}
if (outOfBoundsCount < 50) {
takenSpots.push(spot);
addSpanPositionStyling(span, spot.startX, spot.startY);
}
outOfBoundsCount = 0;
}
function setupDefaultSpot(width, height) {
return {
width: width,
height: height,
startX: centerX - width / 2,
startY: centerY - height / 2,
endX: centerX + width / 2,
endY: centerY + height / 2
};
}
function moveSpotOnSpiral(spot, angleMultiplier) {
var angle = angleMultiplier * 0.1;
spot.startX = centerX + (1.5 * angle) * Math.cos(angle) - (spot.width / 2);
spot.startY = centerY + angle * Math.sin(angle) - (spot.height / 2);
spot.endX = spot.startX + spot.width;
spot.endY = spot.startY + spot.height;
return spot;
}
function spotNotUsable(spot) {
var borders = {
left: centerX - scope.width / 2,
right: centerX + scope.width / 2,
bottom: centerY - scope.height / 2,
top: centerY + scope.height / 2
};
for (var i = 0; i < takenSpots.length; i++) {
if (spotOutOfBounds(spot, borders) || collisionDetected(spot, takenSpots[i])) return true;
}
return false;
}
function spotOutOfBounds(spot, borders) {
if (spot.startX < borders.left ||
spot.endX > borders.right ||
spot.startY < borders.bottom ||
spot.endY > borders.top) {
outOfBoundsCount++;
return true;
} else {
return false;
}
}
function collisionDetected(spot, takenSpot) {
if (spot.startX > takenSpot.endX || spot.endX < takenSpot.startX) {
return false;
}
return !(spot.startY > takenSpot.endY || spot.endY < takenSpot.startY);
}
function addSpanPositionStyling(span, startX, startY) {
var style = "position: absolute; left:" + startX + "px; top: " + startY + "px;";
span.attr("style", style);
span.removeClass("tangcloud-item-hidden");
}
};
}
};
return directive;
}]);
The tang-cloud directive is defined as tangCloud - take this example from the angular docs for directive
app.js
.directive('myCustomer', function() {
return {
template: 'Name: {{customer.name}} Address: {{customer.address}}'
};
});
index.html
<div ng-controller="Controller">
<div my-customer></div>
</div>
See the Normalization section in this part of the docs. Try searching 'tangCloud'

How can I load youtube videos with angularjs?

I am trying to delay loading of youtube videos via javascript code as explained here.
and here is the code for that:
function optimizeYouTubeEmbeds() {
// Get all iframes
var frames = document.getElementsByTagName('iframe');
// Loop through each iframe in the page.
for (var i = 0; i < frames.length; i++) {
// Find out youtube embed iframes.
if (frames[i].src && frames[i].src.length > 0 && frames[i].src.match(/http(s)?:\/\/www\.youtube\.com/)) {
// For Youtube iframe, extract src and id.
var src = frames[i].src;
var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
var id = (src.match(p) ? RegExp.$1 : false);
if (id == false) { continue; }
// Get width and height.
var w = frames[i].width;
var h = frames[i].height;
if (src == '' || w == '' || h == '') { continue; }
// Thease are to position the play button centrally.
var pw = Math.ceil(w / 2 - 38.5);
var ph = Math.ceil(h / 2 + 38.5);
// The image+button overlay code.
var code = '<img src="http://i.ytimg.com/vi/' + id + '/hqdefault.jpg" style="" />';
// Replace the iframe with a the image+button code.
var div = document.createElement('div');
div.innerHTML = code;
div = div.firstChild;
frames[i].parentNode.replaceChild(div, frames[i]);
i--;
}
}
}
// Replace preview image of a video with it's iframe.
function LoadYoutubeVidOnPreviewClick(id, w, h) {
var code = '<iframe src="https://www.youtube.com/embed/' + id + '/? autoplay=1&autohide=1&border=0&wmode=opaque&enablejsapi=1" width="' + w + '" height="' + h + '" frameborder=0 allowfullscreen style="border:1px solid #ccc;" ></iframe>';
var iframe = document.createElement('div');
iframe.innerHTML = code;
iframe = iframe.firstChild;
var div = document.getElementById("skipser-youtubevid-" + id);
div.parentNode.replaceChild(iframe, div);
}
This code worked before switching my project to the angular way of doing things.
I initially thought I could just wrap that code in a $scope and call it, but that did not work. Here is my code that retrieves the videos:
$scope.renderHtml = function (html) {
return $sce.trustAsHtml(html);
};
$scope.Videos = [];
$scope.getVideos = function() {
// api call
$http.get('/api/Videos/AllVideos')
.success(function(data) {
$scope.Videos = data;
});
};
$scope.getVideos();
and here is the html tag where it is rendered:
<div ng-repeat="vid in Videos">
<div ng-bind-html="renderHtml(vid.url)"></div>
</div>
The vid.url includes all the iframe tag information etc. What do I need to do to make this work?

Resources