I'd like to have a responsive graph using Chart.js on my Svelte app. The size of the chart should follow the browser window size. I currently have a chart on a div container. However, it doesn't work expectedly, as I expected the chart is getting bigger when the browser window size is bigger. It gets smaller when I downsize the browser window.
It seems that the container size is following the browser size but the chart canvas. I tried to control the canvas size programmatically by adding the code below.
const clientHeight = document.getElementsByClassName('chart-container')[0].clientHeight;
const clientWidth = document.getElementsByClassName('chart-container')[0].clientWidth;
chart.canvas.height = clientHeight;
chart.canvas.width = clientWidth;
I got the height and width of the container, but it didn't work too. What can I do more?
Here is the code.
<script>
import { onMount } from 'svelte';
import Chart from 'chart.js/auto';
let data = [20, 100, 50, 12, 20, 130, 45];
let labels = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
let ctx;
let canvas;
onMount(() => {
ctx = canvas.getContext('2d');
var chart = new Chart(ctx, {
options: {
layout: {
responsive: true,
maintainAspectRatio: false
}
},
type: 'bar',
data: {
labels: labels,
datasets: [
{
label: 'Unit Sales',
data: data
}
]
}
});
});
</script>
<div >
<canvas bind:this={canvas} />
</div>
<style>
div {
position: relative;
height: 100vh;
width: 100vw;
}
</style>
CodePudding user response:
It's not
options: {
layout: {
responsive: true,
maintainAspectRatio: false
}
},
but
options: {
maintainAspectRatio: false
},