hls.js play backward and forward by currentTime - hlsl

I play the video by currentTime property forward, but sometimes the video stop and for few second, the video jump forward. You can see the seeked function below.
How do I use currentTime property to play instead of play() function. Here is a demo below.
<video id="video" controls></video>
<button id="test">Play</button>
video {
width: 600px;
height: 300px;
}
var video = document.getElementById('video')
var hls = new Hls({
// debug: true
})
hls.loadSource('https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8')
hls.attachMedia(video)
video.pause()
var testBtn = document.getElementById('test')
var timer = null
let index = 0;
video.addEventListener('seeked', () => {
console.log('seeked', index++); // something it stop and run, this is abnormal
})
testBtn.addEventListener('click', () => {
clearInterval(timer)
// seek to 00:00
video.currentTime = 0
// play forwards
timer = setInterval(() => {
video.currentTime += 0.05
}, 50)
})
demo

Related

Chartjs how to add animations to legend labels, ticks and other elements

In the same way the bars / datasets animates "Out of the box", how can I also add animations to the labels, ticks and the grid when the chart first loads?
I looked through the docs but don't see anything about animating these elements? However on their landing page is claims "Animate everything!"
I managed to get one element animated doing the following:
new Chart(ctx, {
type: 'bar',
data: chart_data,
options: {
animation: {
onComplete: () => {
delayed = true;
},
onProgress: function(animation) {
if(!delayed) {
//this works
this.options.scales.x.grid.borderWidth = animation.currentStep / animation.numSteps;
//this needs to work but doesn't
this.options.scales.x.grid.borderDash = [animation.currentStep / animation.numSteps * 10, 20];
//I've tried other elements here, but none of them change, only this.options.scales.x.grid.borderWidth for some reason
}
},
delay: (context) => {
let delay = 0;
if (context.type === 'data' && context.mode === 'default' && !delayed) {
delay = context.dataIndex * 300 + context.datasetIndex * 100;
}
return delay;
},
}...`
However it doesn't seem to work on anything else.

Google Places Web API incorrectly throwing error and breaking maps on nearbySearch

I'm attempting to pull some places from the Places Web API in order to draw some markers on a map. It seems like it is incorrectly throwing an error:
Uncaught Error: Missing parameter. You must specify location.
in places_impl.js:35
My code follows:
var bounds = map.getBounds();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
bounds: bounds,
type: ['natural_feature']
}, callback);
and it should work as per the documentation:
This method takes a request with the following fields:
Either of:
bounds, which must be a google.maps.LatLngBounds object defining the rectangular search area; or
a location and a radius; the former takes a google.maps.LatLng object, and the latter takes a simple integer, representing the circle's radius in meters. The maximum allowed radius is 50 000 meters. Note that when rankBy is set to DISTANCE, you must specify a location but you cannot specify a radius or bounds.
https://developers.google.com/maps/documentation/javascript/places#place_search_requests
The issue is that bounds is not valid when you are calling the service.
The map is initialized asynchronously, the bounds isn't available until the bounds_changed event fires for the first time.
Wait until the 'bounds_changed' event fires on the map before using map.getBounds().
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
bounds: bounds,
type: ['natural_feature']
}, callback);
});
proof of concept fiddle
code snippet:
var geocoder;
var map;
var infowindow = new google.maps.InfoWindow();
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
bounds: bounds,
type: ['natural_feature']
}, callback);
});
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places"></script>
<div id="map_canvas"></div>

Save graph as image after click link full script

I have this code
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.2.js"></script>
<script type="text/javascript" src="js/chart-js/Chart.js"></script>
<script type="text/javascript">
var data = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
},
{
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green"
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow"
}
];
$(document).ready(
function () {
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).Pie(data);
document.getElementById("canvas_link").src = document.getElementById("myChart").toDataURL();
}
);
</script>
</head>
<body>
<p>save as image</p>
<canvas id="myChart" width="400" height="400"></canvas>
<p>export to pdf</p>
</body>
I need create pdf export and add into image with gener graph. Berofe I must save render image. I try use method .toBase64Image() but I dont know have can I start.
My proceed
create canvas_link (.toDataUrl). After click save as image I can greate and upload image to server. Then I can generate pdf export (across mPDF) and to add imageto into export. This i can create, but I dont know create and upload image of graph to server.
I need more examples from http://www.chartjs.org/docs/
in that case you don't need to upload as an image.
you could put the result of the call to toDataUrl function in the value of a hidden field and send it in a form (with an iframe as target) or by an ajax call
use the following options in the chart
//new options var
var options = {
bezierCurve : false,
//animation: false
onAnimationComplete: done
};
//your code with a little modification
$(document).ready(
function () {
var ctx = document.getElementById("myChart").getContext("2d");
//use the previously defined "options" here!!!
var myNewChart = new Chart(ctx).Pie(data, options);
}
);
//callback function, called when the pie ends his animation
function done(){
//this part of your code was moved here to avoid that store an empty image
document.getElementById("canvas_link").src = document.getElementById("myChart").toDataURL();
var postdata={
file: document.getElementById("myChart").toDataURL()
}
$.post( "store.php", postdata)
.done(function( ret ) {
console.log( "Data status: Loaded successfully ");
})
.fail(function( ret ) {
console.log( "Data status: error ");
})
;
}
Reference: http://api.jquery.com/jquery.post/
in php you can handle the content in this way
// file: store.php
// Interpret data uri
$uriPhp = 'data://' . substr($file, 5);
// Get content
$binary = file_get_contents($uriPhp);
$file = 'uploads/charts/'. time() .'.png';
// Save image
file_put_contents($file, $binary);
Reference: https://github.com/nnnick/Chart.js/issues/99#issuecomment-75359927
As per the documentation, you can print or save graph by API calls;
Example
var chart = new CanvasJS.Chart("chartContainer", {
theme: "theme2",
title:{
text: "Print Chart using print() method"
},
data: [
{
type: "column",
dataPoints: [
{ label: "apple", y: 10 },
{ label: "orange", y: 15 },
{ label: "banana", y: 25 },
{ label: "mango", y: 30 },
{ label: "grape", y: 28 }
]
}
]
});
chart.render();
document.getElementById("printChart").addEventListener("click",function(){
chart.print();
//chart.exportChart({format: "jpg"});
});

translate3d with a transition not being accelerated (being blocked by JS)

I am trying to animate a (100% width) div offscreen by moving it using translate3d(100%,0,0) with a 1s transition. I believe the animation should be fully offloaded to the GPU and not affected by JS, but it is freezing as I do JS computations.
Note that it doesn't freeze when I use a pixel value, e.g. translate3d(500px,0,0)
See this in effect: http://jsfiddle.net/khufzte9/
This is the code I'm using:
CSS:
html, body {
margin: 0;
padding: 0;
}
#blue {
background-color: blue;
width: 100%;
height: 100%;
-webkit-transition: all 1s;
}
HTML:
<div id='blue'></div>
JS:
document.body.addEventListener('click', function () {
var blue = document.querySelector('#blue');
blue.style.transform = 'translate3d(100%,0,0)';
// Do some blocking work after the animation starts
setTimeout(function () {
for (var i = 0; i < 1000000000; i++) {
var j = 5/3;
}
}, 300);
});
Any thoughts or advice would be much appreciated!

Unit testing AngularJS and Flot Charts

I am trying to unit test (Jasmine) AngularJS and Flot Charts but receive the following errors. I do not receive these errors in the console of my application and the charts render as expected.
PhantomJS 1.9.2 (Mac OS X) Charts Directive should populate the container element FAILED
TypeError: 'undefined' is not an object (evaluating 'placeholder.css("font-size").replace')
at parseOptions (/Library/WebServer/Documents/zui/app/js/libs/flot/jquery.flot.js:740)
at Plot (/Library/WebServer/Documents/zui/app/js/libs/flot/jquery.flot.js:673)
at /Library/WebServer/Documents/zui/app/js/libs/flot/jquery.flot.js:3059
at /Library/WebServer/Documents/zui/app/js/directives/charts.js:6
at /Library/WebServer/Documents/zui/app/js/libs/angular.js:7942
at /Library/WebServer/Documents/zui/test/unit/directives/charts.spec.js:10
at /Library/WebServer/Documents/zui/test/unit/directives/charts.spec.js:23
at invoke (/Library/WebServer/Documents/zui/app/js/libs/angular.js:2902)
at workFn (/Library/WebServer/Documents/zui/app/js/libs/angular-mocks.js:1795)
at /Library/WebServer/Documents/zui/app/js/libs/angular-mocks.js:1782
at /Library/WebServer/Documents/zui/test/unit/directives/charts.spec.js:24
PhantomJS 1.9.2 (Mac OS X): Executed 30 of 40 (1 FAILED) (0 secs / 0.126 secs)
Charts Directive:
FAILED - should populate the container element TypeError: 'undefined' is not an object (evaluating 'placeholder.css("font-size").replace')
at parseOptions (/Library/WebServer/Documents/zui/app/js/libs/flot/jquery.flot.js:740)
at Plot (/Library/WebServer/Documents/zui/app/js/libs/flot/jquery.flot.js:673)
at /Library/WebServer/Documents/zui/app/js/libs/flot/jquery.flot.js:3059
at /Library/WebServer/Documents/zui/app/js/directives/charts.js:6
at /Library/WebServer/Documents/zui/app/js/libs/angular.js:7942
at /Library/WebServer/Documents/zui/test/unit/directives/charts.spec.js:10
at /Library/WebServer/Documents/zui/test/unit/directives/charts.spec.js:23
at invoke (/Library/WebServer/Documents/zui/app/js/libs/angular.js:2902)
at workFn (/Library/WebServer/Documents/zui/app/js/libs/angular-mocks.js:1795)
at /Library/WebServer/Documents/zui/app/js/libs/angular-mocks.js:1782
at /Library/WebServer/Documents/zui/test/unit/directives/charts.spec.js:24
PhantomJS 1.9.2 (Mac OS X): Executed 31 of 40 (1 FAILED) (0 secs / 0.134 secs)
Directive:
angular.module('directives.FlotCharts', [])
.directive('flotChart', function () {
return {
restrict: 'EA',
controller: ['$scope', '$attrs', function ($scope, $attrs) {
var plotid = '#' + $attrs.id,
model = $scope[$attrs.ngModel];
$scope.$watch('model', function (x) {
$.plot(plotid, x.data, x.options);
});
}]
};
});
Controller:
angular.module('Charts', ['directives.FlotCharts'])
.controller('diskChartCtrl', ['$scope', function ($scope) {
$scope.model = {};
$scope.model.data = [
{
label: "Available",
data: 20,
color:"#00a34a"
},
{
label: "Used",
data: 100,
color:"#c00"
}
];
$scope.model.options = {
series: {
pie: {
innerRadius: 0.5, // for donut
show: true,
label: {
formatter: function (label, series) {
return '<div class="pie">' + label + ': ' +
series.data[0][1] + 'GB <br>(' + Math.round(series.percent) + '%)</div>';
}
}
}
},
legend: {
show: false
}
};
}])
}]);
Test Spec:
describe('Charts Directive', function () {
var scope, html, tmpl, ctrl, $compile;
var compileTmpl = function (markup, scope) {
var el = $compile(markup)(scope);
scope.$digest();
return el;
};
beforeEach(function () {
module('directives.FlotCharts');
module('Charts');
inject(function ($rootScope, _$compile_, $controller) {
$compile = _$compile_;
scope = $rootScope.$new();
ctrl = $controller('diskChartCtrl', {$scope: scope});
html = angular.element('<div data-flot-chart id="disk" data-chart="pie" data-status="danger" data-ng-model="model" data-ng-controller="diskChartCtrl"></div>');
tmpl = compileTmpl(html, scope);
});
});
it('should populate the container element', function () {
expect(true).toBe(true);
//expect(tmpl.html()).toContain('canvas');
});
});
Any insight is greatly appreciated.
This may not be the answer to your question, but hopefully it will help steer you in the right direction. Here's the source of the exception from jquery.flot.js:
fontDefaults = {
style: placeholder.css("font-style"),
size: Math.round(0.8 * (+placeholder.css("font-size").replace("px", "") || 13)),
variant: placeholder.css("font-variant"),
weight: placeholder.css("font-weight"),
family: placeholder.css("font-family")
};
It appears that placeholder.css('font-size') is returning undefined. I seem to remember hearing of some problems with jQuery.css('margin') not working in PhantomJS, but jQuery.css('margin-left') behaving correctly.
If you explicitly set style: "font-size: 10px;" on the element do you get different results? I noticed you were setting the directive's class to pie, have you included any stylesheets?
I was able to solve this issue as commented by compiling the markup against rootScope and setting inline width and height styles. It may have been an issue of missing width and height properties.
inject(['$rootScope', '$compile', '$controller', function ($rootScope, $compile, $controller) {
scope = $rootScope.$new();
ctrl = $controller('itemChartCtrl', { $scope: scope });
tmpl = '<div data-flot-chart id="items" data-chart="pie" data-status="danger" data-ng-model="model" data-ng-controller="itemChartCtrl" style="width:300px;height:300px"></div>';
$compile(tmpl)($rootScope);
}]);