I'm using Charts.js library and my <canvas> element is acting strangely when i try to re scale it by changing it's width and height attributes
I'm definitely missing something , keep in mind that i capture the whole window
here are some examples:
width=400 , height=100
width="100" height="100"
width="10" height="20"
width="400" height="50"
Try it here , this is supposed to be a 10x10 square (pretty small right?)
var ctx = document.getElementById('myChart');
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
}
}]
}
}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<canvas id="myChart" width="10" height="10"></canvas>
Why can't i make it a 100x100 square? and not be placed in the whole browser?do i need a placeholder for this?
Here is the playground that makes a graph non-resizable as you might notice in the desktop view although the mobile view is perfect
Desktop View
Mobile View
Note:
When <div> is not included and <canvas> has not attributes in browser it's huge , and on mobile resolution is perfect. If you apply width and height to <div> which contains <canvas> you can resize it but on mobile will be stretched.
Edit: added code snippet
Edit2: added code playground
This is happening because you have "reponsive" activated by default. In this case , the attributes width and height will be ignored.
The solution is to desactivate the responsive option like this :
options: {
responsive:false,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
If you look at it through your console, you will notice that an extra element div.chartjs-size-monitor is added to the DOM right before your target canvas.
This is done by ChartJS to ensure the canvas can be resized properly.
To solve the it, you simply need to
Move the canvas into a container element
Set your size at the container element.
Note that the parent element must be display: block (i.e., div).
ChartJS will change the width and height attribute of your canvas anyway, so there is no point setting it from your end.
var ctx = document.getElementById('myChart');
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
}
}]
}
}
});
/* CODE BELOW ONLY EXIST TO IMITATE BROWSER SIZE */
const wrapper = document.querySelector('#window');
const desktop = document.querySelector('#desktop');
const mobile = document.querySelector('#mobile');
desktop.addEventListener('click', resize.bind(this, 'desktop'));
mobile.addEventListener('click', resize.bind(this, 'mobile'));
function resize(size, event){
event.preventDefault();
wrapper.classList.remove('desktop', 'mobile')
wrapper.classList.add(size);
}
/* CSS HERE ONLY EXIST TO IMITATE BROWSER SIZE */
#window {
margin-top: 10px;
border: 1px solid black;
transition: all 0.3s;
}
#window.desktop {
width: 450px;
height: 253px;
}
#window.mobile {
width: 320px;
height: 568px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<!-- Ignore these -->
<button id="desktop">Desktop</button>
<button id="mobile">Mobile</button>
<!-- #window is to imitate browser window size -->
<!-- imagine #container as the direct children of <body> -->
<div id="window" class="desktop">
<!-- Moved all CSS to HTML as your requirement -->
<div id="container" style="width: 100%; height: 100%; position: relative;">
<canvas id="myChart"></canvas>
</div>
</div>
Related
I'm creating a mood tracker that allows people to input the number of days they feel a certain mood. The HTML form accepts the numbers from 0-7, and accordingly I want the pie chart to dynamically shift to reflect that value. When I tried inserting the value in the data array, the whole chart disappears instead. I can't seem to figure out what the issue is, this is my code for reference:
``div class="form-container" style="float: left; margin-left: 170px; margin-top: 13px; text-align: center;">
<form>
<!---Mood Chart--->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div class="chart-container" style=" float: right; margin-right: 150px;position: relative; height: 42vh; width: 42vw; margin-top: 8px">
<canvas id="myChart" width="100px" height="100px"></canvas>
<script>
const ctx = document.getElementById('myChart');
const myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: [],
datasets: [{
label: '# of Votes',
data: [angryValue.value, sadValue.value, happyValue.value, anxiousValue.value, tiredValue.value, motivatedValue.value],
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: {
}
}
});
function updateChart(){
angryValue = Number(document.getElementById('angry').value);
sadValue = Number(document.getElementById('sad').value);
happyValue = Number(document.getElementById('happy').value);
anxiousValue = Number(document.getElementById('anxious').value);
motivatedValue = Number(document.getElementById('motivated').value);
tiredValue = Number(document.getElementById('tired').value);
data.push({
angry: angryValue,
sad: sadValue,
happy: happyValue,
anxious: anxiousValue,
motivated: motivatedValue,
tired: tiredValue
});
chart.render();
}
var moodBtn = document.getElementById('mood-btn');
moodBtn.addEventListener('click', updateChart);
</script>
</div>``
Maybe this is more what you want?
const moods=['Angry', 'Sad', 'Happy', 'Anxious', 'Motivated', 'Tired'];
const ctx = document.getElementById('myChart');
const cont=document.querySelector(".form-container");
cont.innerHTML=moods.map((M,i)=>{
let m=M.toLowerCase();
return `<input type="text" name="${m}" placeholder="${M}" value="${i+2}"> ${M}`;
}).join("<br>");
const inps=[...document.querySelectorAll("input")];
cont.addEventListener("input",ev=>{
myChart.data.datasets[0].data= inps.map(el=>+el.value);
myChart.update()
});
const myChart = new Chart( ctx, {
type: 'pie',
data: {
labels: moods,
datasets: [{
label: '# of Votes',
data: inps.map(el=>+el.value),
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: {}
}
});
.form-container,.chart-container {margin: 8px; display:inline-block;}
#myChart { width:200px; height:200px;}
.form-container input {width:30px}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div class="form-container"></div>
<div class="chart-container"><canvas id="myChart"></canvas></div>
I replaced some of your lengthy HTML markup by some generated code, based on the moods array. I also skipped the buttons and triggered the update() event by listening to input events on the container wrapping all input elements:
cont.addEventListener("input",ev=>{
myChart.data.datasets[0].data= inps.map(el=>+el.value);
myChart.update()
});
Inside the updateChart() function, there is no variable named data. So, it looks like you're pushing some data to the uninitialized variable.
Isn't the data supposed to be pushed inside the config of chart.js? You might want to create a separate variable for storing the data so that you can push the data on the fly from other functions and just swap out the data for chart.js.
<div class="form-container" style="float: left; margin-left: 170px; margin-top: 13px; text-align: center;">
<form>
<!---Happy--->
<div class="mood">
<input type="string" name="happy" id="happy" placeholder="Happy" value="1" required>
<button class="mood-btn" >Enter</button>
</div>
<!---Angry--->
<div class="mood">
<input type="string" name="angry" id="angry" placeholder="Angry" value="3" required>
<button class="mood-btn" >Enter</button>
</div>
<!---Sad--->
<div class="mood">
<input type="string" name="sad" id="sad" placeholder="Sad" value="5" required>
<button class="mood-btn" >Enter</button>
</div>
<!---Motivated--->
<div class="mood">
<input type="string" name="motivated" id="motivated" placeholder="Motivated & Productive" value="6"required>
<button class="mood-btn" >Enter</button>
</div>
<!---Tired--->
<div class="mood">
<input type="string" name="tired" id="tired" placeholder="Tired or Burnt out" value="0" required>
<button class="mood-btn" >Enter</button>
</div>
<!---Anxious--->
<div class="mood">
<input type="string" name="anxious" id="anxious" placeholder="Anxious & Stressed" value="7" required>
<button class="mood-btn" >Enter</button>
</div>
</form>
</div>
<!---Mood Chart--->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div class="chart-container" style=" float: right; margin-right: 150px;position: relative; height: 42vh; width: 42vw; margin-top: 8px">
<canvas id="myChart" width="100px" height="100px"></canvas>
<script>
let chartData =[]
const ctx = document.getElementById('myChart');
const myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['Angry', 'Sad', 'Happy', 'Anxious', 'Motivated', 'Tired'],
datasets: [{
label: '# of Votes',
data: chartData,
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: {
}
}
});
function removeData(chart) {
chart.data.datasets.forEach((dataset) => {
dataset.data.pop();
});
chart.update();
}
function addData(chart, data) {
chart.data.datasets.forEach((dataset) => {
dataset.data = [...data]
});
chart.update();
}
function updateChart(event){
event.preventDefault()
angryValue = Number(document.getElementById('angry').value);
sadValue = Number(document.getElementById('sad').value);
happyValue = Number(document.getElementById('happy').value);
anxiousValue = Number(document.getElementById('anxious').value);
motivatedValue = Number(document.getElementById('motivated').value);
tiredValue = Number(document.getElementById('tired').value);
chartData = [
angryValue,
sadValue,
happyValue,
anxiousValue,
motivatedValue,
tiredValue
]
removeData(myChart)
addData(myChart, chartData)
}
var moodBtn = document.querySelectorAll('.mood-btn');
moodBtn.forEach(btn => {
btn.addEventListener('click', updateChart, false)
})
</script>
</div>
I am creating a dashboard that has multiple Chart.js. The dashboard has sidebar navigation which can be minimized when clicking the toggle button. Which increases the width of the container.
The chart does not fit its container to its height as you can see in the image.
but If I add CSS for the canvas tag it will use the height that is specified in the CSS. But its stretches the chart and makes it blury.
Also If I toggle the sidebar to minimize, the width of the chart increases but when I toggle to maximize the size of sidebar, the width of chart does not decrease according to the width of main container. As you can see, the dark part expanded outside the viewport.
HTML:
<div class="graph1">
<div>
<h5>Profit & Loss (Column Grouped Chart)</h5>
<canvas id="myChart1"></canvas>
</div>
<div>
<h5>Fuel Consumed (Litres)</h5>
<canvas id="myChart2"></canvas>
</div>
<div>
<h5>Fleet Usage</h5>
<canvas id="myChart3"></canvas>
</div>
</div>
CSS:
.graph1 {
position: relative;
display: grid;
grid-template-columns: 2fr 1fr 1fr;
grid-gap: 1rem;
height: 26rem;
margin-bottom: 1.5rem;
& > div {
padding: 1rem;
box-shadow: 0px 3px 6px #00000029;
border-radius: 0.6rem;
}
canvas {
width: 100%;
min-height: 26rem;
}
}
JS:
/*Chart1*/
var ctx = document.getElementById('myChart1').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange', 'Red'],
datasets: [
{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3, 12],
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)',
'rgba(255, 99, 132, 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)',
'rgba(255, 99, 132, 1)',
],
borderWidth: 1,
},
],
},
options: {
responsive: true,
maintainAspectRatio: true,
// scales: {
// y: {
// beginAtZero: true,
// },
// },
},
});
I just coded my first chart in chart.js, but i cant move it to the center of my webpage
here is my code for the chart in html:
Use "display:block;margin:0 auto;" to center the div containing the JS table.
Make a container for your canvas and give it display: inline-block style. Then you can treat the container like any html block.
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'line',
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
}
}]
}
}
});
.outbox{
text-align: center;
}
.container{
width: 50%;
display: inline-block;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<div class="outbox">
<div class="container">
<canvas id="myChart" width="400" height="400"></canvas>
</div>
</div>
You want to center the canvas since that is where the chart is drawn on. To center the canvas see this stack article: How to center canvas in html5
I have a file named index.html in my Chrome extension that uses ChartJS to draw a chart. This is the markup :
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome to dashboard</title>
<link rel="stylesheet" href="./style.css">
<script src="scripts/Chart.min.js"></script>
</head>
<body>
<canvas id="chart" height="400" width="900"></canvas>
<script src="./script.js"></script>
</body>
And this is the script:
var ctx = document.getElementById("chart").getContext('2d');
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
}
}]
}
}
});
I am not getting any error in console. But still, the page is rendered blank. What could be the issue with this code?
<script src="https://raw.githubusercontent.com/nnnick/Chart.js/master/dist/Chart.bundle.js"></script>
<script>
var ctx = document.getElementById("mycanvas");
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
}
}]
}
}
});
</script>
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Dashboard</div>
<div class="panel-body">
<canvas id="mycanvas" height="280" width="600"></canvas>
</div>
</div>
</div>
</div>
</div>
i am getting nothing from this code its not showing chart i am using chartjs
anyone tell me whats wrong i am doing here i am using it on larave 5.2 if any one suggest how to do it on laravel 5.2 i really appreciate it please someone help
As of now the code is executed with page content be loaded in DOM. You need to wait for DOM to build. You should use DOMContentLoaded event
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
//Your code
});
Additionally, github is not a CDN thus don't refer to JavaScript file stored there directly.
https://raw.githubusercontent.com/nnnick/Chart.js/master/dist/Chart.bundle.js
Gives 404 not found error. Please use your servers or a CDN to serve this file.
check this JSFiddle
you need to use a working cdn like: https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.bundle.js
HTML
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Dashboard</div>
<div class="panel-body">
<canvas id="mycanvas" height="280" width="600"></canvas>
</div>
</div>
</div>
</div>
</div>
JS
var ctx = document.getElementById("mycanvas");
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
}
}]
}
}
});
Try this Working Example
var ctx = document.getElementById("mycanvas");
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
}
}]
}
}
});
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Dashboard</div>
<div class="panel-body">
<canvas id="mycanvas" height="280" width="600"></canvas>
</div>
</div>
</div>
</div>
</div>