I'm new to electron so I'm learning the basic configuration.
So, i want to implement chart.js in my electron app.
The problem is: on my main page, the chart is simply a blank space... but with a look in the html inspector I can see the canvas created.
What I already did:
I've installed chart.js with npm install chart.js --save which we can find in the official chart.js documentation (https://www.chartjs.org/docs/latest/getting-started/installation.html).
My feeling tells me that I'm doing something wrong in the call for the chart library or something like that. My code is below:
<canvas id="myChart"></canvas>
<script>
const { chart } = require('electron-chartjs');
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45]
}]
},
// Configuration options go here
options: {}
});
</script>
As you can see, I'm using the official example. The only addition was the const { chart } = require('electron-chartjs');. So, I believe I'm doing something wrong or ignoring some big step.
Update:
Here is the new code:
<canvas id="chart"></canvas>
<script>
var Chart = require('chart.js');
var ctx = document.getElementById('chart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45]
}]
},
// Configuration options go here
options: {}
});
</script>
I had to require "chart.js", but i was requiring "electron-chart,js". And the canvas id was wrong.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script>
// ** entire Chart.js library **
</script>
<style>
</style>
</head>
<body>
<canvas id="myChart"></canvas>
<script>
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: {{chartData}}
}
]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).Line(data);
</script>
</body>
</html>
Notice the placeholder {{chartData}}. Also do note that you have to substitute in the actual script from the Chart.js file (you could link to the script file, but then you'll need a module that serves up static files)
var http = require('http');
var fs = require('fs');
http.createServer(function (req, response) {
fs.readFile('index.html', 'utf-8', function (err, data) {
response.writeHead(200, { 'Content-Type': 'text/html' });
var chartData = [];
for (var i = 0; i < 7; i++)
chartData.push(Math.random() * 50);
var result = data.replace('{{chartData}}', JSON.stringify(chartData));
response.write(result);
response.end();
});
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
We just substitute the placeholder with actual data.
Update for electron 21.2.0.
Download chart.js module from npm
Modify Index.html:
Add 'unsafe-inline' in meta
<meta http-equiv="Content-Security-Policy" content="default-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'">
Now we can use chart.js as usual.
I only have no idea how to set custom width/height of my chart ):
Demo code is available on:
https://github.com/zdzmzych/electronNoiseAnalyzer
Related
I've plots build with 2 different versions of chart.js. one is with 3.8.0 & other is with 2.8.0. So, I'm including both the versions in tags like this.
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.8.0"></script> #For plot1
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script> #for plot2
-->Both are color plots. so whenever i use js#3.8.0 first It's plotting plot1 as color. But, plot2 I'm getting with no color's.
-->Similarly when I use js#2.8.0 as first src
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script> #for plot2
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.8.0"></script> #For plot1
plot1I'm getting withno color&plot2withcolor` 😐
I get it that in Html executes script src line by line. is there is any way to use different chartjs versions at a time?. Any reference pls?
You guys want to upload the code?. It's a very big source code. So, I just want to get thoughts for my issue from the community people
Chart.js #3.8.0 version code I'm using
Fiddle https://jsfiddle.net/rnsbhargav/x10qjr5k/3/
graph2() {
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
segment: {
borderColor: (ctx) => (ctx.p0.parsed.y < ctx.p1.parsed.y ? 'green' : 'red')
}
}]
},
options: {}
}
const ctx = document.getElementById('mychart').getContext('2d');
new Chart(ctx, options);
},
So this in chartjs 3.8.0. Should I need to downgrade syntax?. If so how to make this code work on chartjs 2.0 version...
I found After digging some documentation I came to know that syntax migrated for #chartjs2 to chartjs3 is different...
so is there is anyway
I can modify the code & get same output with chartjs#2 version?
Is there is any way we can use .noconflict method we use normally on Jquery? so that i can use 2 different versions on source tags
https://www.chartjs.org/docs/master/getting-started/v3-migration.html
You can load the old version of chart.js, store it in a variable, then load the new version also store it and then you can use both, as you can see in the example below old version filled by default and had beziercurves enabled, v3 does not fill by default and has sharp lines:
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<canvas id="chartJSContainer2" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<script>
const chartOld = Chart;
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>
<script>
const chartNew = Chart;
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'orange'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'pink'
}
]
},
options: {}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
const ctx2 = document.getElementById('chartJSContainer2').getContext('2d');
new chartNew(ctx, options);
new chartOld(ctx2, options);
</script>
</body>
I'm using Mapbox GL JS and Chart.js to visualize a map with clickable markers. When clicked on a marker a Chart.js graph should be shown in the Mapbox popup, with the graph based on information of the clicked marker. Right now, this is how I achieve it:
var i = 0;
map.on("click", "trips", function (e) {
var coordinates = e.features[0].geometry.coordinates.slice();
var nTripsMonth = e.features[0].properties.nTripsMonth;
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML('<canvas id="foo' + i + '"></canvas>')
.addTo(map);
map.flyTo({center: e.features[0].geometry.coordinates, zoom: 18});
var ctx = document.getElementById('foo' + i).getContext('2d');
console.log(ctx)
var chart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Distribution',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: nTripsMonth
}]
},
});
i++;
});
This works the way I want it, however I feel like this is not the correct way.
I have a page full of charts that automatically generates all charts available (because the default page is "All Charts"). In it, there's a select department tag that will hide all charts other than those owned by the selected department. Here's my code:
$(window).load(function(){
$('#department').change(function(){
active_department($(this).val());
});
function active_department(department){
for(var i = 0; i < dept['namedept'].length; i++){
if(department!='All'){
$('.'+dept['namedept'][i]).hide(500);
} else {
if(typeof rCharts[dept['namedept'][i]] != 'undefined'){
$('.'+dept['namedept'][i]).show(500);
} else {
$('.no-chart-'+dept['namedept'][i]).hide(500);
}
}
}
if(typeof rCharts[department] != 'undefined'){
$('.'+department).show(500);
} else {
$('.no-chart-'+department).hide(500);
}
}
});
I want ChartJS animation to re-appear every time I select a department. So far I've tried easing, onProgress, and jQuery animate. none's working. Is it possible to re-animate the chart? If so, how?
From this answer and from the lack of options available in the Docs, it looks like the only feasible options would be these hacks:
redraw the chart with JS using new Chart or
change some minor configuration, or recreate an instance of the chart data and then call the update() method.
e.g.: Call the data through a function, and when you want the animation to happen, call the same function again. Because it now has a new array (even though it's the same data), the chart re-animates.
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<button onclick="updateChart()">Update</button>
<canvas id="myChart"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var chartData = {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: createDataset()
}
};
var chart = new Chart(ctx, chartData);
function updateChart(){
chartData.data.datasets = createDataset()
chart.update();
}
function createDataset(){
return [{
label: "My First dataset",
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45],
fill: false
}];
}
//ignore next line, it's to deal with a bug from chartjs cdn on stackoverflow
console.clear();
</script>
Apart from the documentation I read (usually not helpful), I found some chart examples I want to implement to my page, but it seems not working. I tried to tweak it around but every time it gets load, it always displaying blank on the page.
Here's the code:
<div data-ng-controller="LineCtrl as line">
<canvas> data-sys-chart-line
data-dataset="line.data"
width="400"
height="240"></canvas>
</div>
<script type="text/javascript">
(function () {
'use strict';
function LineCtrl ( ) {
this.data = {
labels: ["January", "February", "March", "April", "May", "June"],
datasets: [
{
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
data: [40, 10, 60, 70, 20, 20]
},
{
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
data: [30, 70, 40, 90, 60, 70]
}
]
};
}
})();
</script>
<!-- Includes Dependencies here: AngularJS & Chart.js -->
<script src="script/Chart.js"></script>
<script src="script/angular-chart.min.js"></script>
<script src="script/tc-angular-chartjs.min.js"></script>
<script>
I included those .js files under /script folder in my project folder.
i have never used Chart.js before but seems that u are doing it wrong
you have never initialize the chart, by reading the documentation like for 10 second i found that you have to initialize it like this
var ctx = document.getElementById("here_is_the_canvas_element").getContext('2d');
var myChart = new Chart(ctx, { ... })
and you are using Chart.js code before you include the library
I want to use charts in my HTML-pages, which i make in a web project made with VS 2015.
So i installed the NuGet-package Chart.js:
Description for installation of Chart.js
After the installation i see two new JS-scripts in the scripts-folder:
Charts.js and Charts.min.js
Next i tried to implement a line diagram/chart in my page.
<!DOCTYPE html>
<html>
<head>
<title>Display charts with Chart.js</title>
<script type="text/javascript" src="../scripts/Chart.min.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<form>
<h3>Example for display of chart data</h3>
<canvas id="buyers" height="600" width="400"></canvas>
<script type="text/javascript">
var buyerData = {
labels: ["January", "February", "March", "April", "May", "June"],
datasets: [
{
fillColor: "rgba(172,194,132,0.4)",
strokeColor: "#ACC26D",
pointColor: "#fff",
pointStrokeColor: "#9DB86D",
data: [203, 156, 99, 251, 305, 247]
}
]
}
var buyers = document.getElementById("buyers").getContext("2d");
new Chart(buyers).Line(buyerData);
</script>
</form>
</body>
</html>
But each time i try to start the page, i get a message, that the property Line does not exist.
What's wrong?
Thanks in advance!
I have found a solution, but i'm not absolutely sure about it.
If want to post other answers, You are invited.
I replaced the line
new Chart(buyers).Line(buyerData);
by
var myChart = new Chart(buyers, { type: 'line', data: buyerData });
Further i discovered another option:
var myChart = Chart.Line(buyers, { data: buyerData });