Canvas is not defined for simple chart - javascript

I'm trying to put a simple chart on my website. I have this code:
<script src="http://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<script>
var ctx = canvas.getContext("2d");
var parent = document.getElementById('parent');
canvas.width = parent.offsetWidth;
canvas.height = parent.offsetHeight;
var chart = new Chart(ctx, {
type: 'line',
options: {
legend: {
display: false
},
responsive: true,
maintainAspectRatio: false
},
data: {
labels: [3,4],
datasets: [{
label: 'Test 01',
data: [1,2],
}
]
}
});
</script>
<div id="parent">
<canvas id="myChart"></canvas>
</div>
However it returns me the error:
Uncaught ReferenceError: canvas is not defined
at mytest3.html:47
I've tried moving the canvas above and below the script but it doesn't make a difference. What am I doing wrong here?

You also need to get the canvas like
var canvas = document.getElementById('myChart')

You need to set the canvas variable before you use it. Add the following:
<script>
//Add the following line
var canvas = document.getElementById("myChart");
var ctx = canvas.getContext("2d");

You need to put the script AFTER the element exists. You need to define canvas....
<script src="http://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<!-- Need to put canvas before the script -->
<div id="parent">
<canvas id="myChart"></canvas>
</div>
<script>
var canvas = document.getElementById("myChart"); // <-- need to define canvas
var ctx = canvas.getContext("2d");
var parent = document.getElementById('parent');
canvas.width = parent.offsetWidth;
canvas.height = parent.offsetHeight;
var chart = new Chart(ctx, {
type: 'line',
options: {
legend: {
display: false
},
responsive: true,
maintainAspectRatio: false
},
data: {
labels: [3,4],
datasets: [{
label: 'Test 01',
data: [1,2],
}
]
}
});
</script>

Related

Chart.js - Unable to refresh the page

I have X and Y coordinates that come from a robot.
I want to update the chart so that the data is displayed separately as a car moves.
The error throws: Cannot read property "data" of undefined.
Could someone help me, how can i get the upgrade to succeed?
var ros = new ROSLIB.Ros({
url:'ws://10.0.2.5:9090'
});
var tag5617 = new ROSLIB.Topic({
ros:ros,
name:"/dwm1001/tag5617",
messageType:"dwm1001/anchor"
});
var myChart;
var canvas = document.getElementById('myChart');
var ctx = canvas.getContext('2d');
function init(){
const myChart = new Chart(ctx, {
type: 'scatter',
data: {
datasets: [{
label: 'GOKART MOVING',
data: [{x:1,y:1}],
backgroundColor: ['#087037'],
}],
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
suggestedMax: 20,
}
}]
, xAxes: [{
ticks:{
suggestedMax:15,
}
}]
}
}
});
}
init();
tag5617.subscribe(function(message) {
//console.log("X: " + message.x);
//console.log("Y: " + message.y);
let X = document.getElementById('posX');
X.innerHTML = message.x.toFixed(2);
let Y = document.getElementById('posY');
Y.innerHTML = message.y.toFixed(2);
myChart.data.datasets[0].push({X,Y});
myChart.update();
});
You define 2 myChart. So your first declaration stay empty ;)
Re-assign your variable, don't make a new who stay in your init function scope.
function init(){
myChart = new Chart(ctx, {
...
});
}

Show image instead a point in a ChartJS scatter plot

I am trying to replace points of a scatter plot with a PNG image. Based on the documentation, the pointStyle accepts either a string or an image. However instead of the image on the first point, it just shows a regular scatter plot point. Any ideas?
var ctx = document.getElementById("myChart").getContext('2d');
var img = new Image();
var img1 = img.src = 'assets/img/small/STORM.png';
var imageData = {
datasets: [{
pointStyle: [img1, 'rect', 'triangle', 'circle'],
data: [{
x: 1.447377,
y: -0.014573
}, {
x: 2.365398,
y: -1.062847
}, {
x: -2.507778,
y: 0.389309
}, {
x: -0.432636,
y: 0.124841
}]
}]
}
var myChart = new Chart(ctx, {
type: 'scatter',
data: imageData,
options: {}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0/dist/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
You can see a working example in jsfiddle here
According to Chart.js documentation, pointStyle is either a string or an Image but not an array.
If you want to have individual styles for your points, you can use the Plugin Core API. It offers several hooks that may be used for executing custom code. You could use the afterDraw hook to assign a different pointStyle to each point.
plugins: {
afterUpdate: function(chart) {
const meta = chart.getDatasetMeta(0);
meta.data[0]._model.pointStyle = img;
meta.data[1]._model.pointStyle = 'rect';
meta.data[2]._model.pointStyle = 'triangle';
meta.data[3]._model.pointStyle = 'circle';
}
},
I your amended code below, I used a slightly different but more compact approach and defined the pointStyles array outside of the chart configuration.
const img = new Image();
img.src = 'https://i.stack.imgur.com/gXQrT.png';
const pointStyles = [img, 'rect', 'triangle', 'circle'];
new Chart(document.getElementById('myChart'), {
type: 'scatter',
plugins: {
afterUpdate: chart => {
chart.getDatasetMeta(0).data.forEach((d, i) => d._model.pointStyle = pointStyles[i]);
}
},
data: {
datasets: [{
data: [
{x: 1.447377, y: -0.014573},
{x: 2.365398, y: -1.062847},
{x: -2.507778, y: 0.389309},
{x: -0.432636, y: 0.124841}
],
backgroundColor: ['white', 'green', 'red', 'orange'],
pointRadius: 10
}]
},
options: {
legend: {
display: false
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="90"></canvas>

How to create a multi line chart with with dynamic x and y axis in one graph using chart js?

I want to create a multi line chart with dynamically changing values of x and y axis.Value for my Y axis are
traverse1 = [10,20,30,45,65,98]
traverse2 = [10,36,56,44,60,100]
traverse3 = [55,65,90,49,55,13]
traverse4 = [59,68,95,59,35,15]
Values for my X axis are
master = [0.1,0.2,0.3,0.5,,0.6]
All the values of X and Y will change dynamically by user.
I have tried to plot a graph but after changing the value dynamically my graph looks something like this grah. .
As you can see in the graph that for each line there is a seperate labels for X axis. What I want is common x axis for all the lines in the graph. Below Is the code that I have used to plot the graph.
function chartCall(master, traverse1, traverse2, traverse3, traverse4)
{
var canvas = document.getElementById("barChart");
var ctx = canvas.getContext('2d');
// Global Options:
Chart.defaults.global.defaultFontColor = 'black';
Chart.defaults.global.defaultFontSize = 16;
var dataFirst = {
label: "Traverse 1",
data: traverse1,
borderColor: "rgb(151,187,205)",
};
var dataSecond = {
label: "Traverse 2",
data: traverse2,
borderColor: "rgb(220,220,220)",
};
var dataThird = {
label: "Traverse 3",
data: traverse3,
borderColor: "rgb(247,70,74)",
};
var dataFourth = {
label: "Traverse 4",
data: traverse4,
borderColor: "rgb(70,191,189)",
};
var speedData = {
labels: master,
datasets: [dataFirst,dataSecond,dataThird,dataFourth]
};
// Chart declaration:
var myBarChart = new Chart(ctx, {
type: 'line',
data: speedData,
options: {}
});
}
the chart seems to draw fine with the code posted in the question,
even after changing the values and calling again.
see following working snippet,
click the button to update the chart with different values...
$(document).ready(function() {
var traverse1 = [10,20,30,45,65,98];
var traverse2 = [10,36,56,44,60,100];
var traverse3 = [55,65,90,49,55,13];
var traverse4 = [59,68,95,59,35,15];
var master = [0.1,0.2,0.3,0.5,,0.6];
chartCall(master, traverse1, traverse2, traverse3, traverse4);
document.getElementById('update').addEventListener('click', function () {
var traverse1 = getRandomValues(6);
var traverse2 = getRandomValues(6);
var traverse3 = getRandomValues(6);
var traverse4 = getRandomValues(6);
var master = [0.1,0.2,0.3,0.5,,0.6];
chartCall(master, traverse1, traverse2, traverse3, traverse4);
});
function chartCall(master, traverse1, traverse2, traverse3, traverse4) {
var canvas = document.getElementById("barChart");
var ctx = canvas.getContext('2d');
// Global Options:
Chart.defaults.global.defaultFontColor = 'black';
Chart.defaults.global.defaultFontSize = 16;
var dataFirst = {
label: "Traverse 1",
data: traverse1,
borderColor: "rgb(151,187,205)",
};
var dataSecond = {
label: "Traverse 2",
data: traverse2,
borderColor: "rgb(220,220,220)",
};
var dataThird = {
label: "Traverse 3",
data: traverse3,
borderColor: "rgb(247,70,74)",
};
var dataFourth = {
label: "Traverse 4",
data: traverse4,
borderColor: "rgb(70,191,189)",
};
var speedData = {
labels: master,
datasets: [dataFirst,dataSecond,dataThird,dataFourth]
};
// Chart declaration:
var myBarChart = new Chart(ctx, {
type: 'line',
data: speedData,
options: {}
});
}
function getRandomValues(length) {
var values = [];
for (var i = 0; i < length; i++) {
values.push(Math.random() * 10);
}
return values;
}
});
<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.7.2/Chart.bundle.min.js"></script>
<input id="update" type="button" value="Update Chart" />
<canvas id="barChart"></canvas>

Chart.js line doesn't fit in

The line which consist of points with maximum doesn't fit in chart... I tried to use responsive, edit height - all the same.
var ctx = document.getElementById('chart').getContext('2d');
var colors = ['#3e95cd', '#8e5ea2', '#3cba9f', '#e8c3b9', '#c45850'];
var datasets = [];
for (var id in data) {
datasets.push({
data: Object.values(data[id].items),
label: data[id].name,
borderColor: colors.pop(),
fill: false
})
}
window.myLine = Chart.Line(ctx, {
type: 'line',
data: {
labels: Object.keys(data[1].items),
datasets: datasets,
},
options: {
responsive: true,
title: {
display: true,
text: _DATE.clone().subtract(_PERIOD, 'days').format('YYYY-MM-DD') + ' - ' + _DATE.format('YYYY-MM-DD')
}
}
});
You have to increase the height of the canvas
For example:
<div style="height: 200px" id="chart"> </div>
or in your css file.
I hope this helps.

Want to multiple charts on same page with different data

I am using a doughnut chart plugin in my website. It is working fine but I want multiple chart on same page with different data. Please see the code below.
This is the chart I am using
<canvas id="chart-area1" width="200" height="200" style="width:150px !important; height:150px !important;"/></canvas>
Script is here
<script src="http://www.chartjs.org/assets/Chart.min.js"></script>
<script>
var doughnutData = [
{
value: 45,
color:"#17CB8A",
highlight: "#17CB8C",
label: "Strating"
},
{
value: 12,
color: "#FF003C",
highlight: "#FF003A",
label: "Warning"
},
{
value: 7,
color: "#fb6800",
highlight: "#fb6801",
label: "Past Due"
},
{
value: 9,
color: "#88c100",
highlight: "#88c102",
label: "In Progress"
},
];
window.onload = function(){
var ctx = document.getElementById("chart-area1").getContext("2d");
window.myDoughnut = new Chart(ctx).Doughnut(doughnutData, {responsive : true});
};
</script>
How I can copy this chart with different attributes?
This is how i did it. with multiple canvases.
<script>
var doughnutData = [ ... ];
var doughnutData2 = [ ... ];
var doughnutData3 = [ ... ];
window.onload = function(){
var ctx = document.getElementById("chart-area1").getContext("2d");
var dtx = document.getElementById("chart-area2").getContext("2d");
var etx = document.getElementById("chart-area3").getContext("2d");
window.myDoughnut = new Chart(ctx).Doughnut(doughnutData, {responsive : true});
window.myDoughnut2 = new Chart(dtx).Doughnut(doughnutData2, {responsive : true});
window.myDoughnut3 = new Chart(etx).Doughnut(doughnutData3, {responsive : true});
};
</script>
If you want to use multiple Charts on same canvas you can use the fork FVANCOP did for Chart.js here

Categories

Resources