Scaling HTML5 canvas width preserving w/h aspect ratio(缩放 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 纵横比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:缩放 HTML5 画布宽度保留 w/h 纵横比


基础教程推荐
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01