我在一个容器内有一个chart.js画布,我给它指定了最小宽度,以便人们可以在移动设备上滚动图表。
但是,只要容器具有固定的宽度,图表就会变得越失真,屏幕越小。
在图表中,我已经尝试设置选项var blogPosts = $('#blog-posts'); // get reference once to avoid repeat lookups
$.each(byMonth, function(key, value) {
var outer = byMonth[key]
$.each(outer, function(k, v) {
var inner = outer[k];
var jData = JSON.stringify(v);
var monthBlogPosts = $('<div class = "month"> </div>').appendTo(blogPosts);
// ^ obtain reference here
$.each(inner, function(i, obj) {
var title = inner[i].Title;
var description = inner[i].Description;
var date = inner[i].DatePublished;
$('<div class = "post"><h2>' + title + '</h2><p>'
+ description + '</p>').appendTo(monthBlogPosts);
// ^ use reference here
})
}
和responsive: true
。这样可以解决问题,但图表仍然失真。
Chart.js选项:
maintainAspectRatio: false
HTML:
var options = {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
stacked: false,
gridLines: {
display: true,
color: "rgba(151,151,151,0.2)"
}
}],
xAxes: [{
gridLines: {
display: true,
color: "rgba(151,151,151,0.2)"
}
}]
}
};
CSS:
<div class="tds-chart-inner tds-hor-scroll">
<canvas id="tds-chart-mem"></canvas>
</div>
工作表
扭曲的图表
答案 0 :(得分:1)
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
</head>
<style>
.tds-chart-inner {
width:100%;
}
</style>
<body class="">
<div class="tds-chart-inner tds-hor-scroll">
<canvas id="myChart"></canvas>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js">
</script>
<script>
var ctx = document.getElementById("myChart").getContext('2d');
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,80],
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,
fontColor: 'red'
}
}]
}
}
});
</script>
答案 1 :(得分:1)
对我来说,问题在于图形本身的高度要比我自己设置的画布高。
我的解决方法是:
responsive: true,
maintainAspectRatio: false,
在示例中问题的问题是在CSS中:
canvas {
left: 0px;
height: 300px !important;
}
我会将其更改为:
.tds-hor-scroll {
overflow-x: auto;
}
.tds-chart-inner {
min-width: 850px;
height: 300px;
}
<div class="tds-hor-scroll">
<div class="tds-chart-inner">
<canvas id="tds-chart-mem"></canvas>
</div>
</div>