Fill an array with real-time data - javascript

I have a robot in my project that moves and gives me x and y coordinates. I also get 2 data in roughly 1 second. I would like to ask if I can get this data to be loaded into an array so that I can work with it afterwards.
I would like to display this in a figure later, but for this to happen, I think we need to populate the array with the data.
index.html:
html>
<head>
<script type="text/javascript" src="https://static.robotwebtools.org/roslibjs/current/roslib.min.js">
</script>
<script type="text/javascript" src="main.js">
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
</head>
<body>
<h1 style="text-align: center;">Topic visualization</h1>
<div>
<h3 id="positionX" style="text-align: center;">X:<span id="posX"></span></h3>
<h3 id="positionY" style="text-align: center;">Y:<span id="posY"></span></h3>
</div>
</body>
<canvas id="myChart" width="500" height="150"></canvas>
<script>
/////////////////////////////
let array = [];
array.push(document.getElementById("posX"))
console.log(array)
////////////////////////////
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'GOKART MOVING',
data: posX//call the function later,
}],
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
suggestedMax: 20,
}
}]
}
}
});
</script>
</html>
main.js:
//Connecting and message print out
var ros = new ROSLIB.Ros({
url:'ws://10.0.2.10:9090'
});
ros.on('connection',function(){
console.log("Connected to websocket server")
});
ros.on('error',function(){
console.log("Error connecting to websocket server: ",error)
});
ros.on('close',function(){
console.log("Connection to websocket server closed.")
});
var tag5617 = new ROSLIB.Topic({
ros:ros,
name:"/dwm1001/tag5617",
messageType:"dwm1001/anchor"
});
tag5617.subscribe(function(message) {
//console.log("X: " + message.x);
//console.log("Y: " + message.y);
let h2_x = document.getElementById('posX');
h2_x.innerHTML = message.x.toFixed(2);
let h2_y = document.getElementById('posY');
h2_y.innerHTML = message.y.toFixed(2);
});

You can declare this array in global scope, and push the values in the subscription.
const array = [];
tag5617.subscribe(function(message) {
//console.log("X: " + message.x);
//console.log("Y: " + message.y);
let h2_x = document.getElementById('posX');
h2_x.innerHTML = message.x.toFixed(2);
let h2_y = document.getElementById('posY');
h2_y.innerHTML = message.y.toFixed(2);
array.push({x:h2_x, y:h2_y});
});
this will push your x and y values as an object in the array, you can add additional details to the object and later on retrieve it from the array!

Related

Chartjs, scatter with For-Loop

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8" />
<title>Charts</title>
<script src="./OurScript.js" type="text/javascript"></script>
<style>
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
</head>
<body>
<canvas id="myChart1"></canvas>
<script type="text/javascript">//<![CDATA[
var x = new Chart(document.getElementById("myChart1"), {
type: 'scatter',
data: {
datasets: [{
label: "Test",
data: [
{x:0,y:3},{x:1,y:4},{x:2,y:2},{x:3,y:5},{x:4,y:7},{x:5,y:5},{x:6,y:7},{x:7,y:8},{x:8,y:4},{x:9,y:4}
],
}]
},
options: {
responsive: true
}
});
//]]> </script>
</body>
</html>
Thats my Code which works fine. (I need to use XHTML)
My Problem is, I want to use a for Loop for the X and Y Values. But I dont know how to put the Array in data.
I tried something like this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8" />
<title>Charts</title>
<script src="./OurScript.js" type="text/javascript"></script>
<style>
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
</head>
<body>
<canvas id="myChart1"></canvas>
<script type="text/javascript">//<![CDATA[
var xwerte = [0,1,2,3,4,5,6,7,8,9,10];
var ywerte = [3,4,2,5,7,5,7,8,4,4];
var c = [];
var Ergebnis1;
for(var i=0;i<ywerte.length;i++)
{
var obj ="{" + "x:" + xwerte[i] + "," + "y:" + ywerte[i] + "}";
c.push(obj);
}
// alert(c);
var x = new Chart(document.getElementById("myChart1"), {
type: 'scatter',
data: {
datasets: [{
label: "Test",
data: [c],
}]
},
options: {
responsive: true
}
});
//]]> </script>
</body>
</html>
I tried with "alert" and I got the right result. But how should I put "c" in data?
I think I dont see a little (hopefully) mistake.
I need to use XHTML and just JavaScript.
On Snippet there is a error, but as I said, I am using XHTML and there is no Error.
Usually I set up my objects and arrays how I need them at first and then fill them with data.
Set it up:
var chartData = {
datasets: [{
label: 'Test',
data: []
}]
}
Fill it with data:
for (var i = 0; i < yWerte.length; i++) {
chartData.datasets[0].data.push(
{
x: xWerte[i], // You don't need "xWerte", you can simply use "i" when it's always the increment
y: yWerte[i]
}
)
}
You don't need your c to save your data, you can just use it like I did. But if you want c you can save the result of the for-loop in the empty array c and then use chartData.datasets[0].data = c.
Working example with live-preview: https://jsbin.com/copiwefaza/edit?js,output

Creating Table in Google App Script With Date Column

I am currently querying a table from Google sheet which has a Date column. The date column in my dashboard has time info included, which I want to remove; also the starting date in my code is 12/18/2018 but my dashboard starts with one day earlier. 12/17/2018 16.00
My Data source looks like this:
My Dashboard looks like this:
My Code Looks like this.
Code.gs:
function doGet(e) {
return HtmlService
.createTemplateFromFile("Line Chart multiple Table")
.evaluate()
.setTitle("Google Spreadsheet Chart")
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getSpreadsheetData() {
var ssID = "1jxWPxxmLHP-eUcVyKAdf5pSMW6_KtBtxZO7s15eAUag";
var sheet = SpreadsheetApp.openById(ssID).getSheets()[1];
var data1 = sheet.getRange('A2:F9').getValues();
var data2 = sheet.getRange('A2:F9').getValues();
var rows = {data1: data1, data2: data2};
var r = JSON.stringify(rows);
return r;
}
Line Chart multiple Table.html
<!DOCTYPE html>
<html>
<head>
<script src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id="linechartweekly"></div>
<div id="table2"></div>
<div class = "block" id="message" style="color:red;">
<script>
google.charts.load('current', {'packages':['table']});
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(getSpreadsheetData);
function display_msg(msg) {
console.log("display_msg():"+msg);
document.getElementById("message").style.display = "block"; // Style of display
var div = document.getElementById('message');
div.innerHTML = msg;
}
function getSpreadsheetData() {
google.script.run.withSuccessHandler(drawChart).getSpreadsheetData();
}
function drawChart(r) {
// Parse back to an object
var rows = JSON.parse(r);
console.log("rows:"+rows);
var data1 = google.visualization.arrayToDataTable(rows.data1, false);
var data2 = google.visualization.arrayToDataTable(rows.data2, false);
var options1 = {
title: 'SPC Chart weekly',
legend: ['USL', 'UCL', 'Data', 'LCL', 'LSL'],
colors: ['Red', 'Orange', 'blue', 'Orange', 'Red'],
pointSize: 4,
};
var chart1 = new google.visualization.LineChart(document.getElementById("linechartweekly"));
chart1.draw(data1, options1);
var table2 = new google.visualization.Table(document.getElementById("table2"));
table2.draw(data2, {showRowNumber: false, width: '50%', height: '100%'});
}
function failure_callback(error) {
display_msg("ERROR: " + error.message);
console.log('failure_callback() entered. WTF'+error.message);
}
</script>
</body>
</html>
May I know how to change my date to the right format removing the time and also ensure the correct starting date
Any help is much appreciated.
The actual problem has me stumped, but I do have a workaround; see modified code example below, with some additional error handling.
I've extensively tested the server-side function, and from its perspective there is absolutely no difference in the row object that is created whether the range starts at column 'I' or 'J'.
The problem manifests itself in the client-side success handler which, when column 'I' is included is essentially passed a null argument, note the whole object, not just the row.data1 part, is null.
The row object that is being passed from the server to the client is quite complicated (an object with 3 key value pairs, where the values are fairly long arrays). I can't see anything in the GAS documentation that disallows this: Legal parameters and return values are JavaScript primitives like a Number, Boolean, String, or null, as well as JavaScript objects and arrays that are composed of primitives, objects and arrays. So this could be a bug?
The workaround, illustrated in the code examples below is to stringify the object in the server-side function, and then parsing it back to an object in the client.
HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id="table1"></div>
<div id="linechartweekly"></div>
<div id="table2"></div>
<div class = "block" id="message" style="color:red;">
<script>
google.charts.load('current', {'packages':['table']});
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(getSpreadsheetData);
function display_msg(msg) {
console.log("display_msg():"+msg);
document.getElementById("message").style.display = "block"; // Style of display
var div = document.getElementById('message');
div.innerHTML = msg;
}
function getSpreadsheetData() {
google.script.run.withFailureHandler(failure_callback).withSuccessHandler(drawChart).getSpreadsheetData();
}
function drawChart(r) {
// Parse back to an object
var rows = JSON.parse(r);
console.log("rows:"+rows);
var data1 = google.visualization.arrayToDataTable(rows.data1, false);
var data2 = google.visualization.arrayToDataTable(rows.data2, false);
var data3 = google.visualization.arrayToDataTable(rows.data3, false);
var options1 = {
title: 'SPC Chart weekly',
legend: ['USL', 'UCL', 'Data', 'LCL', 'LSL'],
colors: ['Red', 'Orange', 'blue', 'Orange', 'Red'],
pointSize: 4,
};
var table1 = new google.visualization.Table(document.getElementById("table1"));
table1.draw(data1, {showRowNumber: false, width: '50%', height: '100%'});
var chart1 = new google.visualization.LineChart(document.getElementById("linechartweekly"));
chart1.draw(data2, options1);
var table2 = new google.visualization.Table(document.getElementById("table2"));
table2.draw(data3, {showRowNumber: false, width: '50%', height: '100%'});
}
function failure_callback(error) {
display_msg("ERROR: " + error.message);
console.log('failure_callback() entered. WTF'+error.message);
}
</script>
</body>
</html>
Code
function doGet(e) {
return HtmlService
.createTemplateFromFile("Line Chart multiple Table")
.evaluate()
.setTitle("Google Spreadsheet Chart")
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getSpreadsheetData() {
var ssID = "1jxWPxxmLHP-eUcVyKAdf5pSMW6_KtBtxZO7s15eAUag";
var sheet = SpreadsheetApp.openById(ssID).getSheets()[0];
//var firstrow = 6; //11th row
//var range = sheet.getRange(firstrow, 1, sheet.getLastRow() - firstrow + 1, 6);
//var data1 = range.getValues();
var d1 = sheet.getRange('A1:B5').getValues();
var d2 = sheet.getRange('I2:O4').getValues();
var d3 = sheet.getRange('I2:O4').getValues();
var rows = {data1: d1, data2: d2, data3: d3};
// Stringify the object
var r = JSON.stringify(rows);
return r;
}

Plotly.js traces not showing

I'm trying to use Plotly.js to create some graphs of historical cryptocurrency prices, and am running into the problem that my data is not showing up on the graph created. I'm building my code from the sample code at https://plot.ly/javascript/ajax-call/ but tooling it for my own data source and a local copy of plotly-latest.min.js. I'm using a small subset of my data and only one trace to get the code functional, and I've placed console.log statements after the processing of the data and the creation of the trace that show me my data is properly formatted judging by the sample code and its dataset. I've set the range of the chart to the range of my data, but I still see nothing on the chart when its created despite modeling it after working sample code. Where am I going wrong?
My code:
<!DOCTYPE html>
<html>
<head>
<script src="plotly-latest.min.js"></script>
</head>
<body>
<div id="myDiv" style="width: 480px; height: 400px;"></div>
<script>
function makePlot() {
Plotly.d3.csv("bitcoin.csv", function(data){ processData(data) } );
}
function processData(allRows) {
var Date = [], Open = [], High = [], Low = [], Volume = [], MarketCap = [];
for (var i=0; i<allRows.length; i++) {
row = allRows[i];
tmpDate = row['Date;Open;High;Low;Close;Volume;MarketCap'].split(';')[0]
Date.unshift( tmpDate.split('/')[2] + '-' + tmpDate.split('/')[1] + '-' + tmpDate.split('/')[0]);
Open.unshift( row['Date;Open;High;Low;Close;Volume;MarketCap'].split(';')[1]);
High.unshift( row['Date;Open;High;Low;Close;Volume;MarketCap'].split(';')[2]);
Low.unshift( row['Date;Open;High;Low;Close;Volume;MarketCap'].split(';')[3]);
Volume.unshift( row['Date;Open;High;Low;Close;Volume;MarketCap'].split(';')[4]);
MarketCap.unshift( row['Date;Open;High;Low;Close;Volume;MarketCap'].split(';')[5]);
};
makePlotly(Date, Open);
}
function makePlotly(Date, Open) {
var plotDiv = document.getElementById("plot");
var traces = [{
Date: Date,
Open: Open}
];
console.log(traces);
var layout = {
xaxis: {
type: 'date',
title: 'Date',
range: ['2017-11-12', '2017-11-22']
},
yaxis: {
title: 'Price (USD)',
range: [4000, 10000]
},
title: 'Cryptocurrency Historical Prices'
}
Plotly.newPlot('myDiv', traces, layout);
}
makePlot();
</script>
</body>
</html>
bitcoin.csv (1 column)
Date;Open;High;Low;Close;Volume;MarketCap
22/11/2017;8077.95;8302.26;8075.47;8253.55;3633530000;134851000000
21/11/2017;8205.74;8348.66;7762.71;8071.26;4277610000;136967000000
20/11/2017;8039.07;8336.86;7949.36;8200.64;3488450000;134167000000
19/11/2017;7766.03;8101.91;7694.10;8036.49;3149320000;129595000000
18/11/2017;7697.21;7884.99;7463.44;7790.15;3667190000;128425000000
17/11/2017;7853.57;8004.59;7561.09;7708.99;4651670000;131026000000
16/11/2017;7323.24;7967.38;7176.58;7871.69;5123810000;122164000000
15/11/2017;6634.76;7342.25;6634.76;7315.54;4200880000;110667000000
14/11/2017;6561.48;6764.98;6461.75;6635.75;3197110000;109434000000
13/11/2017;5938.25;6811.19;5844.29;6559.49;6263250000;99029000000
12/11/2017;6295.45;6625.05;5519.01;5950.07;8957350000;104980000000
I guess it should be your variable traces causes the problem
var traces = [{
x: Date, //not Date: Date
y: Open //not Open: Open
}];

Duplicate content in pdf created using jsPDF

I am using jsPDF to convert html to pdf. In some cases, where html has svg charts, some of the data is duplicated in the generated pdf.
e.g. If the charts have legends, they are getting duplicated. See the screenshot below. City names and the percentages are repeated.
Below is the code to create pdf.
pdf.addHTML($("#page1"), options, function(){
pdf.addPage();
pdf.addHTML($("#page2"), options, function(){
pdf.addPage();
pdf.output('dataurlnewwindow');
});
});
EDIT 1:
This is what I have figured so far.
<div id="outerDiv">
<div id="pieChart"></div>
</div>
When I do this, pdf.addHTML($("#pieChart"), no issues here.
But, when I do this, pdf.addHTML($("#outerDiv"), then labels get repeated.
and this is how I generate my c3js charts
var pieChart = c3.generate({
bindto: '#pieChart',
EDIT 2:-
Below is my entire code.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script type="text/javascript" src="http://gabelerner.github.io/canvg/rgbcolor.js"></script>
<script type="text/javascript" src="http://gabelerner.github.io/canvg/StackBlur.js"></script>
<script type="text/javascript" src="http://gabelerner.github.io/canvg/canvg.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.5.0-alpha1/html2canvas.js"></script>
<script type='text/javascript'>
function replaceAllSVGsWithTempCanvas(elemSelector) {
var svgElements = $(elemSelector).find('svg');
//replace all svgs with a temp canvas
svgElements.each(function() {
var canvas, xml;
// canvg doesn't cope very well with em font sizes so find the calculated size in pixels and replace it in the element.
$.each($(this).find('[style*=em]'), function(index, el) {
$(this).css('font-size', getStyle(el, 'font-size'));
});
canvas = document.createElement("canvas");
canvas.className = "screenShotTempCanvas";
//convert SVG into a XML string
xml = (new XMLSerializer()).serializeToString(this);
// Removing the name space as IE throws an error
xml = xml.replace(/xmlns=\"http:\/\/www\.w3\.org\/2000\/svg\"/, '');
//draw the SVG onto a canvas
canvg(canvas, xml);
$(canvas).insertAfter(this);
//hide the SVG element
$(this).attr('class', 'tempHide');
$(this).hide();
});
}
jQuery(document).ready(function($) {
genChart();
});
function genPDF() {
var options = {
background: '#fff'
};
var pdf = new jsPDF('p', 'pt', 'a4');
replaceAllSVGsWithTempCanvas(".content");
pdf.addHTML($("#chartOuter"), options, function() {
pdf.output('dataurlnewwindow');
$(".content").find('.screenShotTempCanvas').remove();
$(".content").find('.tempHide').show().removeClass('tempHide');
});
}
function genChart() {
var chart = c3.generate({
data: {
columns: [
['data1', 30],
['data2', 120],
],
type: 'pie'
}
});
}
</script>
</head>
<body class="content">
<table width="100%">
<tr>
<td width="50%">
<div id="chartOuter">
<div id="chart"></div>
</div>
</td>
</tr>
<tr>
<td colspan="2" align="left">
<input type="button" onclick="genPDF();" value="Generate PDF" />
</td>
</tr>
</table>
</body>
</html>
EDIT 3:-
I tried just converting html to canvas using html2canvas. It is also giving the same issue.
Edit 4:
I could fix the duplicate issue now. But the charts and the text written to pdf are little bit blurry. Basically, I added function replaceAllSVGsWithTempCanvas and then use that while writing to pdf. But it seems this function does smething to the html that makes content written to pdf blurry. In fact pie charts etc, are no more circles but looks like oval shape.
Edited the question with modified js.
Looks like it is a bug in html2canvas. You should add the bottom code after html2canvas is loaded to fix that (Credits goes to this guy):
NodeParser.prototype.getChildren = function(parentContainer) {
return flatten([].filter.call(parentContainer.node.childNodes, renderableNode).map(function(node) {
var container = [node.nodeType === Node.TEXT_NODE && node.parentElement.tagName !== "text" ? new TextContainer(node, parentContainer) : new NodeContainer(node, parentContainer)].filter(nonIgnoredElement);
return node.nodeType === Node.ELEMENT_NODE && container.length && node.tagName !== "TEXTAREA" ? (container[0].isElementVisible() ? container.concat(this.getChildren(container[0])) : []) : container;
}, this));
};
Fiddle
Since html2canvas loads as a module, you should directly find NodeParser.prototype.getChildren in the source code and edit it to match above. That means you can't load it from CDN.
I think made it work correctly in two steps.
First, I commented out the "addhtml plugin" because I had this error in my console:
Refused to execute script from 'https://raw.githubusercontent.com/MrRio/jsPDF/master/plugins/addhtml.js' because its MIME type ('text/plain') is not executable, and strict MIME type checking is enabled.
Second, I changed the pdf source from #chartOuter to #chart.
pdf.addHTML($("#chart"), options, function () {
var string = pdf.output('datauristring');
$('.preview-pane').attr('src', string)
});
And there is no more dedoubling.
-----
EDIT (since I misunderstood the question at first)
It is needed to use the outer div... And maybe the full page.
Okay... To be honest, I don't know why this text issue happens.
But I noticed that the duplicate text has serif even if it is specified "sans-serif".
So I focused on this.
I tried to change the font-size... It affected the duplicate, but the text didn't follow the css rule. Okay.
Then I tried to just remove the text before the pdf creation part... And magic!
;)
$(".c3 svg").css({"font-size":"0px"});
Here is the complete script, I didn't touch the rest of your original code.
jQuery(document).ready(function ($) {
genChart();
});
function genPDF() {
var options = { background: '#fff'};
var pdf = new jsPDF('p', 'pt', 'a4');
$(".c3 svg").css({"font-size":"0px"}); // <-- This does the trick !
pdf.addHTML($("#chartOuter"), options, function () {
var string = pdf.output('datauristring');
$('.preview-pane').attr('src', string)
});
}
function genChart() {
var chart = c3.generate({
data: {
columns: [
['data1', 30],
['data2', 120],
],
type : 'pie'
}
});
}
You can try using ChartJS instead of C3.
I've adapted your code and tried it with success.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<!-- <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.debug.js"></script> -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.5.0-alpha1/html2canvas.js"></script>
<script type="text/javascript" src="https://raw.githubusercontent.com/MrRio/jsPDF/master/plugins/addhtml.js"></script>
<script type='text/javascript'>
jQuery(document).ready(function ($) {
genChart();
});
function genPDF() {
var options = { background: '#fff'};
var pdf = new jsPDF('p', 'pt', 'a4');
pdf.addHTML($("#chartOuter"), options, function () {
var string = pdf.output('datauristring');
$('.preview-pane').attr('src', string)
});
}
function genChart () {
var ctx = $("#chart");
var options = {};
var myPieChart = new Chart(ctx, {
type: 'pie',
data: {
labels: [
"data1",
"data2"
],
datasets: [{
data: [30, 120],
backgroundColor: [
"#FF6384",
"#36A2EB"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB"
]
}]
},
options: options
});
}
</script>
</head>
<body>
<table width="100%">
<tr>
<td width="50%">
<div id="chartOuter">
<!-- <div id="chart"></div> -->
<canvas id="chart" width="400" height="400"></canvas>
</div>
</td>
<td>
<iframe height="550px" class="preview-pane" type="application/pdf" width="100%" frameborder="0" style="position:relative;z-index:999"></iframe>
</td>
</tr>
<tr>
<td colspan="2" align="left">
<input type="button" onclick="genPDF();" value="Generate PDF"/>
</td>
</tr>
</table>
</body>
</html>
Dynamically loading pdf blurry, the same file official demo is very clear. I can't locate the problem?
Use the chrome browser. Version 73.0.3683.86 (official version) (64-bit)
Here is my codeļ¼š
async process(buffer, index) {
// Processing the decrypted data stream
let uint8Array = new Uint8Array(buffer);
var word = await this.Uint8ToBase64(uint8Array);
var decryptedData = CryptoJS.AES.decrypt(word, this.authorKey, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
// Then turn wordArray to uint8Array
let getUint8Array = await this.wordArrayToU8(decryptedData);
// decryption ends
this.loadingPdf(getUint8Array, index);
},
async loadingPdf(getUint8Array, index) {
// render canvas
let pdf = await pdfjsLib.getDocument({ data: getUint8Array, cMapUrl: cMapUrl, cMapPacked: cMapPacked });
let page = await pdf.getPage(1).then(page => {
return page;
});
let canvas = document.getElementById("the-canvas" + index);
const CSS_UNITS = 96.0 / 72.0;
const DEFAULT_SCALE = 1.7;
const UNKNOWN_SCALE = 0;
let viewport = page.getViewport( DEFAULT_SCALE * CSS_UNITS);
if (canvas.dataset.runed) return;
canvas.width = viewport.width*CSS_UNITS;
canvas.height = viewport.height*CSS_UNITS;
this.canvasW =
this.canvasW > (1000 / viewport.height) * viewport.width
? this.canvasW
: (1000 / viewport.height) * viewport.width;
canvas.style.width = (1000 / viewport.height) * viewport.width;
canvas.dataset.runed = true;
var context = canvas.getContext('2d');
// [Important] Turn off anti-aliasing
context.mozImageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.msImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;
await page.render({
//enableWebGL: true,
// canvasContext: context,
transform: [CSS_UNITS, 0, 0, CSS_UNITS, 0, 0],
// transform: [1, 0, 0, 1, 0, 0],
canvasContext: canvas.getContext("2d"),
viewport: viewport
});
this.loadedPages.push(index)
},

Dynamic Highcharts is not updating

Here is my use case. I am using Flume and Spark Streaming to count the number of events generated from the server. So in the output of the spark i get timestamp and number of events. After every 10 second the old value is erased and new value is written in a file in HDFS.
I have created Spring framework which will pull the data from HDFS convert it to json and push it to Highcharts. So I am trying to generate a live spline chart which will show timestamp in the x-axis and number of count in the y-axis and update it as it gets new data from the spark output after every 10 seconds. But the x-axis is not shifting and I can see 10 zero values in y-axis. So I am unable to get the updated y value. I am sure I am missing something in the java script. Because from the console of the spring i can see the events are updating after every 10 seconds. But its not reflecting in the chart.
I am stuck here for past two weeks and desperately need help. Any help will be much appreciated. Thanks.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="http://code.highcharts.com/highcharts.js" ></script>
<script type="text/javascript" src="http://code.highcharts.com/maps/modules/exporting.js" ></script>
<script type="text/javascript" src="http://code.highcharts.com/modules/drilldown.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript" src="js/app/appStart.js" ></script>
<link type="text/css" href="css/app.css" rel="stylesheet">
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
</head>
<body>
<div class="chart" id="statusChart" >
</div>
</body>
$(function() {
var url = 'statistics';
$.ajax(url).done(function(data) {
loadStatusChart(data);
});
});
function updateStatusSeries(series){
var url = 'statistics';
$.ajax(url).done(function(data) {
var statusCode = data.statusCode[0];
series.addPoint([statusCode.label, statusCode.value], true, true);
});
}
function loadStatusChart(statistics) {
var StatusCode = statistics.statusCode;
var StatusSeries = [];
$.each(StatusCode, function(index, item) {
var timeInSeconds = item.label/1000;
for(var i = 10; i >= 1; i--){
StatusSeries.push({
x : (timeInSeconds - (i*10))*1000,
y : 0
});
}
StatusSeries.push({
x : item.label,
y : item.value
});
})
var x = StatusCode.length;
$("#statusChart").highcharts({
chart : {
type : 'spline',
//animation : Highcharts.svg,
marginRight : 10,
events : {
load : function(){
//set up updating of the chart each second
var series = this.series[0];
setInterval(function (){
updateStatusSeries(series);
}, 10000);
}
}
},
title: {
text: 'Live Data'
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Number of Counts'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('yyyy/mm/dd hh:mm:ss', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{ data: StatusSeries }]
});
};
First, you're getting leading zeroes in the chart because of this code:
for(var i = 10; i >= 1; i--){ // <----- 10
StatusSeries.push({
x : (timeInSeconds - (i*10))*1000,
y : 0 // <----- zero values
});
}
Second, your chart isn't advancing because in this part
events : {
load : function(){
//set up updating of the chart each second
var series = this.series[0];
setInterval(function (){
updateStatusSeries(series); // <----- Not updating series
}, 10000);
}
}
updateStatusSeries(series) actually doesn't update series, thus the chart doesn't get new data and simply stays on the same spot.
To fix that you can either
create a global chart object and use it to access its series, like described here: http://www.highcharts.com/docs/working-with-data/live-data
modify your updateStatusSeries() so that it uses a callback passed to it, like shown here: http://www.in-example.com/?p=316
Also, date formatting (in tooltip.formatter) should be done like so:
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x)

Categories