Scaling HTML5 canvas width preserving w/h aspect ratio

后端 未结 5 1342

I have a canvas element with dimensions of 979X482px and I\'d like to have it stretch to fit the width of any given browser window, keeping the aspect ratio of width/hight 1

5条回答
  •  离开以前
    2021-01-02 06:08

    First you set the width of canvas to 100%

    $('#canvas').css('width', '100%');
    

    then update its height base on its width

    $(window).resize(function(){
       $('#canvas').height($('#canvas').width() / 2.031);
    });
    

    2.031 = 979/482

    But you should not attach to $(window).resize like me... it's a bad behavior

提交回复
热议问题