我正在使用chart.js和最新的v2.7.1版本。我按照这个jsfiddle示例来滚动时创建固定的Y轴效果。它工作得很好,但Retina显示器(iPhone,Macbook等)存在一个问题。
var ctx = document.getElementById("myChart").getContext("2d");
var chart = {
options: {
responsive: true,
maintainAspectRatio: false,
animation: {
onComplete: function(animation) {
var sourceCanvas = myLiveChart.chart.canvas;
var copyWidth = myLiveChart.scales['y-axis-0'].width - 10;
var copyHeight = myLiveChart.scales['y-axis-0'].height + myLiveChart.scales['y-axis-0'].top + 10;
var targetCtx = document.getElementById("myChartAxis").getContext("2d");
targetCtx.canvas.width = copyWidth;
targetCtx.drawImage(sourceCanvas, 0, 0, copyWidth, copyHeight, 0, 0, copyWidth, copyHeight);
}
}
},
type: 'bar',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
}
]
}};
var myLiveChart = new Chart(ctx, chart);
setInterval(function () {
myLiveChart.data.datasets[0].data.push(Math.random() * 100);
myLiveChart.data.labels.push("Test");
var newwidth = $('.chartAreaWrapper2').width() +60;
$('.chartAreaWrapper2').width(newwidth);
$('.chartAreaWrapper').animate({scrollLeft:newwidth});
}, 5000);
.chartWrapper {
position: relative;
}
.chartWrapper > canvas {
position: absolute;
left: 0;
top: 0;
pointer-events:none;
}
.chartAreaWrapper {
overflow-x: scroll;
position: relative;
width: 100%;
}
.chartAreaWrapper2 {
position: relative;
height: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<div class="chartWrapper">
<div class="chartAreaWrapper">
<div class="chartAreaWrapper2">
<canvas id="myChart"></canvas>
</div>
</div>
<canvas id="myChartAxis" height="300" width="0"></canvas>
</div>
如果您在Retina屏幕上查看代码片段(并等待5秒钟进行滚动触发),则Y轴标签非常大,并且看起来像是没有完全渲染一样。非视网膜屏幕上的相同视图看起来很好。在Retina屏幕或任何特定的chart.js解决方法上是否有任何js / css解决方法用于调整大小问题?
(相信the code snippet的此stackoverflow帖子)
答案 0 :(得分:1)
我也遇到了这个问题,原来的小提琴效果很好,只是它没有响应。
关键是原始小提琴没有考虑devicePixelRatio
与使用ChartJS核心的helpers.retinaScale
方法的图表相同的方式。
经过几个小时的摆弄,这是一个非常简单的答案:https://jsfiddle.net/4ydfo4xo/
从原始图表复制比例时,devicePixelRatio
必须应用于drawImage
具体来说,使用
访问像素比率var pixelRatio = myLiveChart.chart.currentDevicePixelRatio;
然后drawImage
参数被更改..
targetCtx.drawImage(sourceCanvas, 0, 0, copyWidth * pixelRatio, copyHeight * pixelRatio, 0, 0, copyWidth, copyHeight);