无法在HTML上改变chart.js的大小。曾尝试在定义一个部分和div标签的同时设置canvas参数,然后明确地在 <style>
. 还使用了 {responsive: true, maintainAspectRatio: false}
毫无进展
Index.html
<html>
<head>
<title>Chart EG</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
</head>
<body>
<canvas id="chart" width="50" height="50"></canvas>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: "http://localhost:8050/api/route1",
type: 'POST',
dataType:'json',
success: function(res) {
console.log(res);
divData='';
var myLabels =[];
var myData =[];
$.each(res, function(key, value) {
console.log(key);
console.log(value);
myLabels.push(key);
myData.push(value);
});
var ctx = document.getElementById("chart");
var myBarChart = new Chart(ctx, {
type: 'pie',
data: {
labels: myLabels,
datasets: [{
label: 'Labels',
data: myData,
backgroundColor: [
'rgba(75, 192, 192, 0.2)',
'rgba(100, 200, 300, 0.2)',
'rgba(200, 192, 72, 0.2)',
'rgba(400, 92, 72, 0.2)',
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(75, 192, 192, 1)',
'rgba(175, 300, 192, 1)',
'rgba(275, 92, 192, 1)',
'rgba(100, 10, 200, 1)',
'rgba(255,99,132,1)'
],
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false
}
});
}
});
});
</script>
</body>
</html>
更新了代码与完整的HTML。忽略这个,因为SO要求我添加更多的细节(无法在HTML上改变chart.js的大小。曾尝试设置canvas参数,同时定义一个section和div标签,然后明确分配高度和宽度在 <style>
.)
这里有一个HTML代码,用于制作两个大小不一的画布,你只需要改变画布标签的高度和宽度属性。你只需要改变canvas标签的高度和宽度属性。
我为两个画布添加了不同的颜色以示区别
var canvas1 = document.getElementById("first");
var ctx1 = canvas1.getContext("2d");
ctx1.fillStyle = "blue";
ctx1.fillRect(0, 0, canvas1.width, canvas1.height);
var canvas2 = document.getElementById("second");
var ctx2 = canvas2.getContext("2d");
ctx2.fillStyle = "red";
ctx2.fillRect(0, 0, canvas2.width, canvas2.height);
<canvas id="first" height="100"></canvas>
<canvas id="second" height="200"></canvas>