3π
β
As from Docs for Chart.js itβs recommended to wrap canvas into container div and change width/height of the container. But basically itβs changing either by given width or height.
Found a more flexible custom solution from lannymcnie that can be used for any canvas responsiveness:
var stage = new createjs.Stage("canvas");
var c = new createjs.Shape();
c.graphics.f("#f00").dc(0,0,50); // Drawn a 100x100 circle from the center
var t = new createjs.Text("Resize the browser/frame to redraw", "24px Arial bold", "#000");
t.x = t.y = 20;
stage.addChild(c, t);
window.addEventListener("resize", handleResize);
function handleResize() {
var w = window.innerWidth-2; // -2 accounts for the border
var h = window.innerHeight-2;
stage.canvas.width = w;
stage.canvas.height = h;
//
var ratio = 100/100; // 100 is the width and height of the circle content.
var windowRatio = w/h;
var scale = w/100;
if (windowRatio > ratio) {
scale = h/100;
}
// Scale up to fit width or height
c.scaleX= c.scaleY = scale;
// Center the shape
c.x = w / 2;
c.y = h / 2;
stage.update();
}
handleResize(); // First draw
html, body {
padding: 0; margin: 0;
overflow:hidden;
}
canvas {
border: 1px solid #f00;
}
<script src="https://code.createjs.com/easeljs-0.8.2.min.js"></script>
<canvas id="canvas" width="800" height="600"></canvas>
16π
- Create Class
.chart-container {
position: relative;
margin: auto;
height: 80vh;
width: 80vw;
}
- Create Div With class chart-container and place canvas tag inside it.
<div class="chart-container">
<canvas id="canvas"></canvas>
</div>
- Chart options, use property
maintainAspectRatio
set to false:
options: {
maintainAspectRatio: false,
responsive: true,
...
}
2π
You can have it responsive and set a different aspect ratio. My issue was that the chart tend to be squeezed on mobile device taking barely no height.
To remedy, with chart.js 3.2.1, I am using the AspectRatio option:
options: {
aspectRatio: 1,
}
This way the chart is square and stay square, you can play with this number usually between 0.5 to 2 to find a ratio that suits you on both displays.
Source:stackexchange.com