英文:
Responsive Chart.js based on a size of a browser window
问题
我想在我的Svelte应用程序上使用Chart.js创建一个响应式图表。图表的大小应该跟随浏览器窗口大小。我目前在一个div
容器上有一个图表。然而,它的工作方式不如预期,我希望当浏览器窗口大小变大时,图表也会变大,当我缩小浏览器窗口时,图表会变小。
似乎容器大小跟随浏览器大小,但图表画布不是。我尝试通过添加以下代码来以编程方式控制画布大小。
const clientHeight = document.getElementsByClassName('chart-container')[0].clientHeight;
const clientWidth = document.getElementsByClassName('chart-container')[0].clientWidth;
chart.canvas.height = clientHeight;
chart.canvas.width = clientWidth;
我获取了容器的高度和宽度,但这也没有起作用。我还能做什么?
以下是代码部分:
<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 class="chart-container">
<canvas bind:this={canvas} />
</div>
<style>
div {
position: relative;
height: 100vh;
width: 100vw;
}
</style>
英文:
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 class="chart-container">
<canvas bind:this={canvas} />
</div>
<style>
div {
position: relative;
height: 100vh;
width: 100vw;
}
</style>
答案1
得分: 4
不是
options: {
layout: {
responsive: true,
maintainAspectRatio: false
}
},
而是
options: {
maintainAspectRatio: false
},
英文:
It's not
options: {
layout: {
responsive: true,
maintainAspectRatio: false
}
},
but
options: {
maintainAspectRatio: false
},
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论