简体   繁体   中英

Only set canvas height when window width is over 768px, otherwise let it default

I am using angular charts to create a bar chart on my page. I only want the height to be set to 80 so it does not take up as much of my page. The issue is that when the size of the page is decreased, on mobile for instance, the chart squishes itself so it is not legible. If I do not set a canvas height, then it is too big on a desktop, but looks great on a screen size smaller than 768px.

How can I set the canvas height to 80 when the screen size is above 768px and let it default on any lesser size. Or set the canvas height to 80 above 768px and to 150 on anything smaller.

I have been pulling my hair out trying to figure this out.

HTML:

<div class="chart-wrapper">
  <div class="chart-title">
    <b>Annual Sales</b>
  </div>
  <div class="chart-stage" ng-controller="BarCtrl">
    <div>
      <canvas id="bar" class="chart chart-bar"
                    chart-data="data" chart-labels="labels" chart-series="series">
      </canvas>
    </div>
  </div>
</div>

I have tried a few different things, but the canvas size does not change at all.

Here is my last attempt:

$(document).ready(function() {
    var $window = $(window);
    var canvas = $('canvas')[0];
    var checkWidth = function() {
        var windowsize = $window.width();
        if (windowsize > 768) {
            canvas.height = 80;
        }
    };
    checkWidth();
    $(window).resize(checkWidth);
});

I should note that I am trying to keep the canvas width to cover the full width of the screen. Which is why I get the squishing effect on a smaller screen.

Here is the codepen I've been using to play around with it: Click here

This is the squishing effect on a smaller screen:

在此处输入图片说明

And here is what happens when I try to use media queries and set the height with CSS (I believe it is necessary to set with javascript):

在此处输入图片说明

You could use CSS:

@media only screen and (min-width:768){
    .canvas {
        height: 80px;
    }
}

It's a little bit cleaner than using the js approach. And, I believe, faster :)

A vanilla js option, ive set 2 height properties but you may only need to set 1

var viewWidth=document.documentElement.clientWidth || window.innerWidth || document.body.clientWidth;
var barHeight=150;
if(viewWidth>768) barHeight=80;

document.getElementById('bar').style.height=barHeight+'px';
document.getElementById('bar').height=barHeight;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM