Chart.js 旋转 支持屏幕旋转与窗口旋转 谁借莪1个温暖的怀抱¢ 2023-01-10 14:51 137阅读 0赞 <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, viewport-fit=cover"/> <title>Untitled Document</title> </head> <body> <style> .chart-container { position: relative; margin: auto; height: 100%; width: 100%; } .bt { background: blueviolet; text-align: center; width: 45px; height: 45px; position: fixed; top: 0; left: 0; } .rotate { transform: rotate(90deg); -ms-transform: rotate(90deg); /* IE 9 */ -moz-transform: rotate(90deg); /* Firefox */ -webkit-transform: rotate(90deg); /* Safari 和 Chrome */ -o-transform: rotate(90deg); /* Opera */ } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js" integrity="sha512-d9xgZrVZpmmQlfonhQUvTR7lMPtO7NkZMkA0ABN3PHCbKA5nqylQ/yWlFAyY6hYgdF1Qh6nYiuADWwKB4C2WSw==" crossorigin="anonymous"></script> <div id="chart-container"> <canvas id="myChart" width="400" height="400"></canvas> </div> <div class="bt" onclick="onRotate()">旋转</div> </body> </html> <script> // 文档地址 var ctx = document.getElementById("myChart").getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', 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 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); let rotateState = 0 var chartContainer = document.getElementById("chart-container"); function onRotate() { if (rotateState === 0) { rotateState = 1 chartContainer.classList.add('rotate') } else { rotateState = 0 chartContainer.classList.remove('rotate') } myChart.options = { responsive: true, responsiveAnimationDuration: 3000 //调整大小后执行动画时间(以毫秒为单位)) } myChart.canvas.parentNode.style.height = document.body.clientWidth + 'px'; myChart.update() } function _orientationchange() { myChart.options = { responsive: true, //调整图表画布的容器大小 maintainAspectRatio: false, //保持原有的宽高比 responsiveAnimationDuration: 3000 //调整大小后执行动画时间(以毫秒为单位)) } if (document.body.clientWidth > document.body.clientHeight) { console.log('|') myChart.canvas.parentNode.style.height = document.body.clientWidth + 'px'; } else { console.log('-') myChart.canvas.parentNode.style.height = document.body.clientWidth + 'px'; } myChart.update() } window.addEventListener("orientationchange", function () { console.log('旋转了') _orientationchange() }, false); </script>
还没有评论,来说两句吧...