在 Chart.js 中设置图表高度

Set height of chart in Chart.js(在 Chart.js 中设置图表高度)
本文介绍了在 Chart.js 中设置图表高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 Chart.js 绘制一个水平条形图,但它一直在缩放图表,而不是使用我从脚本中分配的画布高度.

I want to draw a horizontal bar chart with Chart.js but it keeps scaling the chart instead of using the height I assign the canvas form the script.

有没有办法从脚本中设置图形的高度?

Is there any way to set the height of the graph from the script?

参见小提琴:Jsfiddle

HTML

<div class="graph">
  <div class="chart-legend">

  </div>
  <div class="chart">
    <canvas id="myChart"></canvas>
  </div>
</div>

JavaScript

var ctx = $('#myChart');

ctx.height(500);

var myChart = new Chart(ctx, {
    type: 'horizontalBar',
    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
        }]
    },
    maintainAspectRatio: false,
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});

推荐答案

似乎 var ctx = $('#myChart'); 正在返回一个元素列表.您需要使用 ctx[0] 来引用第一个.高度也是一个属性,而不是一个函数.

Seems like var ctx = $('#myChart'); is returning a list of elements. You would need to reference the first by using ctx[0]. Also height is a property, not a function.

我在我的代码中是这样做的:

I did it this way in my code:

var chartEl = document.getElementById("myChart");
chartEl.height = 500;

这篇关于在 Chart.js 中设置图表高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)