ChartJS not working in Vue - javascript

I am making a little productivity app/game to make my self feel better about all the time I waste. I am using vue and chartjs and the don't seem to play nice with each other.
When I include my <canvas> element in <div id="app">, the one vue is initiated on chartjs fails to render anything. There are no errors or anything. However, when I move <canvas> outside of <div id="app"> it works perfectly. Doesn't anyone have any insight in this?
HTML
<body>
<div id="app">
<div id="header">
<h1>GAME OF LIFE!</h1>
</div>
<div class="character_container">
<div class="health_bar">
<div class="life"></div>
</div>
<div class="character">
<img id="sprite" src="imgs/melee/1.png" width="100" height="100px">
<div class="stats">
<p>ed</p>
<p>3</p>
<p>3</p>
<p>da</p>
<p>adf</p>
<p>adf</p>
</div>
</div>
</div>
<div id="dashboard">
<h2>GAME DATA</h2>
<input type="date" name="viewDate" v-model="viewDate">
</div>
<!-- Doesn't work when canvas inside #app -->
<div class="canvas">
<canvas></canvas>
</div>
</div>
<!-- Works when the canvas is outside #app -->
<!-- <div class="canvas">
<canvas></canvas>
</div> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<script src="vue.js"></script>
<script src="app.js"></script>
</body>
Javascript
const day = ( x => {
let date = (t => new Date(t.getFullYear(), t.getMonth(), t.getDate(), 0, 0, 0))(new Date());
return new Date(date.setDate(date.getDate() + x));
});
const padDate = (x => (x.toString().length <= 1? '0'+ x : x));
const format = (x => formatDate(new Date(x)));
const formatDate = (fd => padDate(fd.getUTCMonth() + 1)+'/'+padDate(fd.getUTCDate())+'/'+fd.getUTCFullYear()+' 00:00');
const serverUrl = 'http://localhost:3000/logs';
const ctx = document.querySelector("canvas").getContext("2d");
const chartConfig = {
type: 'bar',
data: {
labels: [],
datasets: [{
type: 'bar',
label: 'Productivity',
backgroundColor: 'rgba(255, 0, 0, .5)',
borderColor: 'rgba(255, 0, 0, .5)',
data: [],
}, {
type: 'line',
label: 'Code Written',
backgroundColor: 'rgba(0, 255, 0, .5)',
borderColor: 'rgba(0, 255, 0, .5)',
fill: false,
data: [],
}, ]
},
options: {
title: {
text:"Productivity Graph"
},
scales: {
xAxes: [{
type: "time",
display: true,
time: {
format: 'MM/DD/YYYY HH:mm',
round: 'day',
unit: 'day'
}
}],
},
}
};
function fetchData() {
return fetch(serverUrl).then(function (res){
return res.json();
})
}
function dateToISO(date) {
var msec = Date.parse(date);
return new Date(msec).toISOString().substring(0, 10);
}
function updateLog(logData){
const headers = {
headers: {
'Access-Control-Allow-Origin':'*',
'Content-Type': 'application/json'
},
method: "PUT",
body: JSON.stringify(logData)
};
return fetch('http://localhost:3000/logs',headers).then(function(res){
return res.json();
});
}
function runSprite(){
// NOTE https://www.gameart2d.com/the-robot---free-sprites.html
// NOTE Melee(Good) 8, Run(Normal) 8, DEAD(Bad) 10
let path = 'imgs/';
let i = app.sprite.index;
switch (app.sprite.status) {
case 'good':
path += 'melee/';
i = (i >= 26 ? 1 : ++i);
break;
case 'avg':
path += 'run/';
i = (i >= 8 ? 1 : ++i);
break;
case 'bad':
path += 'dead/';
i = (i >= 10 ? 1 : ++i);
break;
}
path += i;
app.sprite.index = i;
document.querySelector('#sprite').src = path + ".png";
}
setInterval(runSprite, 100);
var app = new Vue({
el: '#app',
data: {
viewDate: new Date().toISOString().substring(0, 10),
sprite: {
status: 'good',
index: 1
},
logs: [],
log:{},
chart: chartConfig,
line: '',
productivityMinutesGoal: 560,
projectsMinutesGoal: 300,
health_bar: 100,
visible: true
},
methods : {
updateChart: function(data, build = false){
this.logs = data;
const productivityAverages = this.logs
.map(x => x.productivity)
.reduce((a, b, index, self) => {
const keys = Object.keys(a)
let c = {}
keys.map((key) => {
c[key] = a[key] + b[key]
if (index + 1 === self.length) {
c[key] = c[key] / self.length
}
})
return c
});
const projectsAverages = this.logs
.map(x => x.projects.data[0].grand_total)
.reduce((a, b, index, self) => {
const keys = Object.keys(a)
let c = {}
keys.map((key) => {
c[key] = a[key] + b[key]
if (index + 1 === self.length) {
c[key] = c[key] / self.length
}
})
return c
});
// above 90% equals + to health_bar;
// below 90% equals - to health_bar;
// below 50% should equal death;
this.health_bar += ((projectsAverages.hours * 60 + projectsAverages.minutes) / this.projectsMinutesGoal ) - 90;
this.health_bar += ((productivityAverages.software_development_hours * 60) / this.productivityMinutesGoal ) - 90;
this.health_bar = Math.round(this.health_bar);
document.querySelector('.health_bar .life').setAttribute('style','width:'+ (100 + this.health_bar)+'%;');
const loggedData = this.logs
.map(x => {return {
date:x.date,
projectTimeMinutes:((x.projects.data[0].grand_total.hours * 60) + x.projects.data[0].grand_total.minutes - (projectsAverages.hours * 60 + projectsAverages.minutes)),
productivitySoftwareMinutes: (x.productivity.software_development_hours * 60 - (productivityAverages.software_development_hours * 60))}
})
.sort((a,b) => new Date(b.date) - new Date(a.date));
loggedData.forEach(x => {
this.chart.data.labels.push(format(x.date));
this.chart.data.datasets[0].data.push(x.productivitySoftwareMinutes);
this.chart.data.datasets[1].data.push(x.projectTimeMinutes);
});
// Handle Build default update
if(build){
this.line = new Chart(ctx, this.chart);
}else{
this.line.update();
}
}
},
computed: {
dateIsValid: function (){
return this.friend.name.length == 0 || this.friend.feature.length == 0;
}
},
created: function (){
fetchData().then(function (data){
app.updateChart(data, true);
});
}
});

Here is a StackBlitz for your reference. All this does is allow Vue to have some awareness of what you are doing. Please let me know you have any other questions.
https://vue-wpbxue.stackblitz.io
<template>
<canvas id="canvas" width="800px" height="800px"></canvas>
</template>
<script>
export default {
name: 'App',
methods: {
draw: function(ctx) {
var myChart = new Chart(ctx, {
type: "bar",
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [
{
label: "# of Votes",
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
"rgba(255, 99, 132, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(255, 206, 86, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(255, 159, 64, 0.2)"
],
borderColor: [
"rgba(255,99,132,1)",
"rgba(54, 162, 235, 1)",
"rgba(255, 206, 86, 1)",
"rgba(75, 192, 192, 1)",
"rgba(153, 102, 255, 1)",
"rgba(255, 159, 64, 1)"
],
borderWidth: 1
}
]
},
options: {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true
}
}
]
}
}
});
}
},
mounted: function() {
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.translate(0.5, 0.5);
ctx.imageSmoothingEnabled = false;
this.draw(ctx);
}
}
</script>
<style>
canvas {
background: white;
box-shadow: 0px 2px 3px rgba(0, 0, 0, 0.2);
}
</style>

Related

Creating charts

I need to make a chart at the level with a row in the table, are there any tips on how to implement this enter image description here
I need the chart lines to match the row level in the table
and this code draws a separate chart
const diag = () => {
document.getElementById("canvasic").innerHTML = ' ';
document.getElementById("canvasic").innerHTML = '<canvas id="densityChart" className="canav"></canvas>';
densityCanvas = document.getElementById("densityChart");
//remove canvas from container
Chart.defaults.global.defaultFontFamily = "Arial";
Chart.defaults.global.defaultFontSize = 16;
var densityData = {
label: 'CallVol',
data:calloiList1,
backgroundColor: 'rgba(0,128,0, 0.6)',
borderColor: 'rgba(0,128,0, 1)',
borderWidth: 2,
hoverBorderWidth: 0
};
var densityData1 = {
label: 'PutVol',
data:calloiList3 ,
backgroundColor: 'rgba(255,0,0, 0.6)',
borderColor: 'rgba(255,0,0, 1)',
borderWidth: 2,
hoverBorderWidth: 0
};
var chartOptions = {
scales: {
yAxes: [{
barPercentage: 0.5
}]
},
elements: {
rectangle: {
borderSkipped: 'left',
}
}
};
var barChart = new Chart(densityCanvas, {
type: 'horizontalBar',
data: {
labels: calloiList4,
datasets: [densityData,densityData1],
},
options: chartOptions
}
);
}
enter image description here

yAxis of chartjs is not displayed?

**When i drawChartData the yAxis of chartjs is not displayed. What is the problem, can you help me **
Before
After
there is my script
<script lang="ts">
import { Vue, Component } from "nuxt-property-decorator";
import BarChartComponent from "#/components/chart/BarChartComponent";
import LineChartComponent from "#/components/chart/LineChartComponent";
import moment from "moment"
import traffic from '#/modules/traffic'
import { TrafficCarrierSummary, TrafficCarrierDetail } from "#/type/traffic-carrier-summary";
const FONT_COLOR = "rgba(255, 255, 255, 1)";
const GRID_LINES_SETTING = {
display: true,
drawOnChartArea: true,
color: "rgba(255, 255, 255, .5)",
zeroLineColor: "rgba(255, 255, 255, 1)"
};
#Component({
components: {
BarChartComponent,
LineChartComponent
},
asyncData: async () => {
let searchObject = {
from: moment().subtract(1, 'months').set('date', 1).format('Y-M-D'),
to: moment().subtract(1, 'months').endOf('month').format('Y-M-D'),
}
const response = await traffic.package(searchObject)
return {
searchObject: searchObject,
packageData: response.data,
}
}
})
export default class extends Vue {
width: number = 575
packageData!: Array<TrafficCarrierSummary>
packageDaliy: TrafficCarrierDetail | null = null
selectedPackage: string | null = null
isDayPackage: boolean = false
selectedDaliyDate: any
loading: boolean = false
lineColors = [
'rgba(120, 0, 0,1)',
'rgba(176, 0, 10,1)',
'rgba(234, 57, 51,1)',
'rgba(251,184, 43,1)',
'rgba(255,234, 97,1)',
'rgba( 92, 98, 91,1)',
'rgba( 35, 37, 35,1)',
]
searchObject = {
from: null,
to: null,
} as any
chartDataPackage: any = {};
chartDataCount: any = {};
chartPackageOptions: Chart.ChartOptions = {
responsive: true,
maintainAspectRatio: false,
title: {
display: false,
},
scales: {
yAxes: [
{
scaleLabel: {
display: true,
labelString: 'Data [GB]',
fontColor: "red",
fontSize: 16
},
ticks: {
suggestedMax: 1000,
suggestedMin: 0,
stepSize: 100,
callback: function(value, index, values) {
return value + "GB";
}
}
}
]
}
};
created() {
this.searchObject.from = new Date(moment().subtract(1, 'months').set('date', 1).toDate())
this.searchObject.to = new Date(moment().subtract(0, 'months').endOf('month').toDate())
this.selectedDaliyDate = this.searchObject.from
this.drawChartPackage()
}
async search() {
this.loading = true
let from = moment(this.searchObject.from).format('Y-MM-DD')
let to = moment(this.searchObject.to).format('Y-MM-DD')
const response = await traffic.package({
from: from,
to: to
})
this.packageData = response.data
this.drawChartPackage()
this.loading = false
}
drawChartPackage() {
let dataArr: Array<any> = []
let labels: Array<string> = []
let obj: any = {}
this.packageData.forEach(element => {
if(!labels.includes(element.target_date)){
labels.push(element.target_date)
}
if(!obj[element.package]){
obj[element.package] = []
}
obj[element.package].push(Number(element.data_total) / 1024 / 1024 / 1024)
})
let index = 0
Object.keys(obj).map(key => {
dataArr.push({
label: key,
data: obj[key],
borderColor: this.lineColors[index],
backgroundColor: 'rgba(0,0,0,0)',
type: 'line'
})
index++
})
this.chartDataPackage = {
labels: labels,
datasets: dataArr
}
}
}
</script>

Chartjs Radar chart - How to dynamically highlight one of the gridlines at a specific point

I create a radar chart to display data which comes from my backend. The data is dynamic, but I would like to highlight the gridline at 60 as shown below. Does chartjs have any solution to achieve it?
const gray = "rgb(200, 200, 200)";
const color = Chart.helpers.color;
const config = {
type: 'radar',
data: {
labels: [['Eating', 'Dinner'], ['Drinking', 'Water'], 'Sleeping', ['Designing', 'Graphics'], 'Coding', 'Cycling', 'Running'],
datasets: [{
label: 'My dataset',
backgroundColor: color(gray).alpha(0.2).rgbString(),
borderColor: gray,
pointBackgroundColor: gray,
data: [
80,
90,
60,
65,
78,
97,
55
]
}]
},
options: {
scale: {
gridLines: {
circular: true,
color: [gray, gray, 'blue', gray, gray, gray, gray, gray, gray, gray]
},
ticks: {
beginAtZero: true,
stepsize: 20
},
}
}
};
window.onload = function () {
window.myRadar = new Chart(document.getElementById('chart'), config);
};
<body>
<canvas id="chart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js" integrity="sha512-hZf9Qhp3rlDJBvAKvmiG+goaaKRZA6LKUO35oK6EsM0/kjPK32Yw7URqrq3Q+Nvbbt8Usss+IekL7CRn83dYmw==" crossorigin="anonymous"></script>
</body>
enter code hereSince your data is dynamic, you need to compute scale.gridLines.colors based on the data. This could be done as follows:
const data = [80, 90, 60, 65, 78, 97, 55];
const gridLinesStepSize = 20;
const highlightedGridLine = 60;
const gridLineColors = Array.from(Array(Math.ceil(Math.max(...data) / gridLinesStepSize) + 1).keys())
.map(n => n * 20)
.slice(1)
.map(v => v == highlightedGridLine ? 'blue' : gray);
Please take a look at your amended runnable code and see how it works.
const gray = "rgb(200, 200, 200)";
const color = Chart.helpers.color;
const data = [80, 90, 60, 65, 78, 97, 55];
const gridLinesStepSize = 20;
const highlightedGridLine = 60;
const gridLineColors = Array.from(Array(Math.ceil(Math.max(...data) / gridLinesStepSize) + 1).keys())
.map(n => n * 20)
.slice(1)
.map(v => v == highlightedGridLine ? 'blue' : gray);
new Chart('chart', {
type: 'radar',
data: {
labels: [
['Eating', 'Dinner'],
['Drinking', 'Water'], 'Sleeping', ['Designing', 'Graphics'], 'Coding', 'Cycling', 'Running'
],
datasets: [{
label: 'My dataset',
backgroundColor: color(gray).alpha(0.2).rgbString(),
borderColor: gray,
pointBackgroundColor: gray,
data: data
}]
},
options: {
scale: {
gridLines: {
circular: true,
color: gridLineColors
},
ticks: {
beginAtZero: true,
stepsize: gridLinesStepSize
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>
<canvas id="chart" height="120"></canvas>

How to add text at center of the chart js donut chart

I want to place the text my data values at the center of the chart js donut charts, I don't know how to do that, I checked the chart js official docs, but they didn't provide any information about this, how can I achieve this.
Here is my code:
HTML:
<canvas id="gx_150s_658Ed8745321" width="200" height="120"></canvas>
JS:
var randomScalingFactor = function () {
return Math.round(Math.random() * 100);
};
var gx_150s_658Ed8745321_ctx = document.getElementById('gx_150s_658Ed8745321').getContext('2d');
var gx_150s_658Ed8745321 = new Chart(gx_150s_658Ed8745321_ctx, {
type: 'doughnut',
data: {
labels: ['Utilized', 'Balence'],
datasets: [{
label: 'Utilized',
data: [95, 5],
backgroundColor: [
'rgb(0, 153, 0, 0.7)',
],
borderColor: [
'rgba(54, 162, 235, 2)',
],
borderWidth: 1
}]
},
options: {
legend: {
display: false
},
title: {
display: true,
text: ' Utilized : 95 %'
},
animation: {
animateScale: true,
animateRotate: true
},
}
});
Expected output:
I'm using a simple plug-in:
config = {
options: {
//...
}
//...
plugin: [{
id: 'my-doughnut-text-plugin',
afterDraw: function (chart, option) {
let theCenterText = "50%" ;
const canvasBounds = canvas.getBoundingClientRect();
const fontSz = Math.floor( canvasBounds.height * 0.10 ) ;
chart.ctx.textBaseline = 'middle';
chart.ctx.textAlign = 'center';
chart.ctx.font = fontSz+'px Arial';
chart.ctx.fillText(theCenterText, canvasBounds.width/2, canvasBounds.height*0.70 )
}
}];
}
You still need to calculate what you wan't in the center text (variable theCenterText).
we can use the animation onComplete callback to know when the animation has finished.
then we can calculate the size and placement of the canvas,
and position a label in the center of the canvas.
animation: {
animateScale: true,
animateRotate: true,
onComplete: function() {
var canvasBounds = canvas.getBoundingClientRect();
dataLabel.innerHTML = ' Utilized : 95 %';
var dataLabelBounds = dataLabel.getBoundingClientRect();
dataLabel.style.top = (canvasBounds.top + (canvasBounds.height / 2) - (dataLabelBounds.height / 2)) + 'px';
dataLabel.style.left = (canvasBounds.left + (canvasBounds.width / 2) - (dataLabelBounds.width / 2)) + 'px';
}
},
see following working snippet...
$(document).ready(function() {
var randomScalingFactor = function () {
return Math.round(Math.random() * 100);
};
var canvas = document.getElementById('gx_150s_658Ed8745321');
var dataLabel = document.getElementById('data-label');
var gx_150s_658Ed8745321_ctx = canvas.getContext('2d');
var gx_150s_658Ed8745321 = new Chart(gx_150s_658Ed8745321_ctx, {
type: 'doughnut',
data: {
labels: ['Utilized', 'Balence'],
datasets: [{
label: 'Utilized',
data: [95, 5],
backgroundColor: [
'rgb(0, 153, 0, 0.7)',
],
borderColor: [
'rgba(54, 162, 235, 2)',
],
borderWidth: 1
}]
},
options: {
legend: {
display: false
},
animation: {
animateScale: true,
animateRotate: true,
onComplete: function() {
var canvasBounds = canvas.getBoundingClientRect();
dataLabel.innerHTML = ' Utilized : 95 %';
var dataLabelBounds = dataLabel.getBoundingClientRect();
dataLabel.style.top = (canvasBounds.top + (canvasBounds.height / 2) - (dataLabelBounds.height / 2)) + 'px';
dataLabel.style.left = (canvasBounds.left + (canvasBounds.width / 2) - (dataLabelBounds.width / 2)) + 'px';
}
},
}
});
});
#data-label {
font-size: 20px;
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<canvas id="gx_150s_658Ed8745321" width="200" height="120"></canvas>
<span id="data-label"></span>

How to use JSON data in creating a chart with chartjs?

In my controller I have an Action method that will find all questions in a table called Questions, and the answers for each question.
This Action is of type ContentResult that will return a result serialized in Json format.
public ContentResult GetData()
{
var datalistQuestions = db.Questions.ToList();
List<PsychTestViewModel> questionlist = new List<PsychTestViewModel>();
List<PsychTestViewModel> questionanswerslist = new List<PsychTestViewModel>();
PsychTestViewModel ptvmodel = new PsychTestViewModel();
foreach (var question in datalistQuestions)
{
PsychTestViewModel ptvm = new PsychTestViewModel();
ptvm.QuestionID = question.QuestionID;
ptvm.Question = question.Question;
questionlist.Add(ptvm);
ViewBag.questionlist = questionlist;
var agree = //query
var somewhatAgree = //query
var disagree = //query
int Agree = agree.Count();
int SomewhatAgree = somewhatAgree.Count();
int Disagree = disagree.Count();
ptvmodel.countAgree = Agree;
ptvmodel.countSomewhatAgree = SomewhatAgree;
ptvmodel.countDisagree = Disagree;
questionanswerslist.Add(ptvmodel);
ViewBag.questionanswerslist = questionanswerslist;
}
return Content(JsonConvert.SerializeObject(ptvmodel), "application/json");
}
Now, my problem is the pie chart is not being created and I don't quite know how to push the values to my data structure?
What should I be doing instead?
Here is my script:
#section Scripts {
<script type="text/javascript">
var PieChartData = {
labels: [],
datasets: [
{
label: "Agree",
backgroundColor:"#f990a7",
borderWidth: 2,
data: []
},
{
label: "Somewhat Agree",
backgroundColor: "#aad2ed",
borderWidth: 2,
data: []
},
{
label: "Disgree",
backgroundColor: "#9966FF",
borderWidth: 2,
data: []
},
]
};
$.getJSON("/PsychTest/GetData/", function (data) {
for (var i = 0; i <= data.length - 1; i++) {
PieChartData.datasets[0].data.push(data[i].countAgree);
PieChartData.datasets[1].data.push(data[i].countSomewhatAgree);
PieChartData.datasets[2].data.push(data[i].countDisagree);
}
var ctx = document.getElementById("pie-chart").getContext("2d");
var myLineChart = new Chart(ctx,
{
type: 'pie',
data: PieChartData,
options:
{
responsive: true,
maintainaspectratio: true,
legend:
{
position : 'right'
}
}
});
});
</script>
You need two arrays for creating your chart. One of them indicates titles and another one shows the number of each titles. You have titles in the client side, so you only need the number of each options and it could be fetched from a simple server method like:
[HttpGet]
public JsonResult Chart()
{
var data = new int[] { 4, 2, 5 }; // fill it up whatever you want, but the number of items should be equal with your options
return JsonConvert.SerializeObject(data)
}
The client side code is here:
var aLabels = ["Agree","Somewhat Agree","Disagree"];
var aDatasets1 = [4,2,5]; //fetch these from the server
var dataT = {
labels: aLabels,
datasets: [{
label: "Test Data",
data: aDatasets1,
fill: false,
backgroundColor: ["rgba(54, 162, 235, 0.2)", "rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(153, 102, 255, 0.2)", "rgba(201, 203, 207, 0.2)"],
borderColor: ["rgb(54, 162, 235)", "rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)", "rgb(75, 192, 192)", "rgb(153, 102, 255)", "rgb(201, 203, 207)"],
borderWidth: 1
}]
};
var opt = {
responsive: true,
title: { display: true, text: 'TEST CHART' },
legend: { position: 'bottom' },
//scales: {
// xAxes: [{ gridLines: { display: false }, display: true, scaleLabel: { display: false, labelString: '' } }],
// yAxes: [{ gridLines: { display: false }, display: true, scaleLabel: { display: false, labelString: '' }, ticks: { stepSize: 50, beginAtZero: true } }]
//}
};
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx, {
type: 'pie',
data: dataT,
options: opt
});
<script src="https://github.com/chartjs/Chart.js/releases/download/v2.7.1/Chart.min.js"></script>
<div Style="font-family: Corbel; font-size: small ;text-align:center " class="row">
<div style="width:100%;height:100%">
<canvas id="myChart" style="padding: 0;margin: auto;display: block; "> </canvas>
</div>
</div>
If you are still looking to use json for chart.js charts.
Here is a solution which fetch a json file and render it on chart.js chart.
fetch('https://s3-us-west-2.amazonaws.com/s.cdpn.io/827672/CSVtoJSON.json')
.then(function(response) {
return response.json();
})
.then(function(ids) {
new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels: ids.map(function(id) {
return id.Label;
}),
datasets: [
{
label: "value2",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: ids.map(function(id) {
return id.Value2;
}),
},
{
label: "value",
//backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: ids.map(function(id) {
return id.Value;
}),
},
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Sample Json Data Chart'
}
}
});
});
see running code on jsfiddle here

Categories