缩放HTML5画布宽度,保持w / h宽高比 [英] Scaling HTML5 canvas width preserving w/h aspect ratio

查看:222
本文介绍了缩放HTML5画布宽度,保持w / h宽高比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个尺寸为979X482px的画布元素,我想让它拉伸以适应任何给定浏览器窗口的宽度,保持宽高/高宽1的宽高比为1,我希望高度相对缩放到画布的宽度。有关如何使用javascript / jQuery执行此操作的任何建议吗?

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 to 1, I want the height to scale relative to width of the canvas. Any suggestions as how to go about doing this with javascript/jQuery?

推荐答案

首先将画布的宽度设置为100%

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

2.031 = 979/482

但是你不应该像我一样附上$(window).resize ......这是一个不好的行为

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

这篇关于缩放HTML5画布宽度,保持w / h宽高比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆