javascript - Fullscreen rectangle in Canvas (Android/iOS web app)(javascript - Canvas 中的全屏矩形(Android/iOS 网络应用程序))
问题描述
我在尝试使用 Canvas 在整个浏览器视口上渲染矩形时遇到问题.下面的代码在桌面上运行良好,但在移动设备上(在 iPad mini、Nexus 7 和 Galaxy S4 上测试),矩形只填充了屏幕的一部分(在 iPad 上大约是一半,在其他设备上是三分之二).
I have a problem trying to render a rectangle over the entire browser viewport using Canvas. The code below works fine on desktop, but on mobile devices (tested on iPad mini, Nexus 7 and Galaxy S4), the rectangle only fills a part of the screen (roughly a half on iPad, two thirds on other devices).
ctx.beginPath();
ctx.rect(0, 0, window.innerWidth, window.innerHeight);
ctx.closePath();
ctx.lineWidth = 5;
ctx.strokeStyle = 'rgba(0,0,0,0.5)';
ctx.stroke();
ctx.fillStyle = 'rgba(0,0,0,0.5)';
ctx.fill();
我试过 ctx.scale(1, 1);但这没有用.window.innerWidth 和 window.innerHeight 的值是正确的.即使我使用硬编码值作为矩形的宽度/高度,我也会得到相同的结果.
I tried ctx.scale(1, 1); but that did not work. The values of window.innerWidth and window.innerHeight are correct. And I get the same result even if I use a hardcoded value as the rectangle's width/height.
解决方案:
基于 Ken Fyrstenberg
var ratio = window.devicePixelRatio || 1;
var width = window.innerWidth * ratio;
var height = window.innerHeight * ratio;
ctx.beginPath();
ctx.rect(0, 0, width, height);
ctx.closePath();
ctx.lineWidth = 5;
ctx.strokeStyle = 'rgba(0,0,0,0.5)';
ctx.stroke();
ctx.fillStyle = 'rgba(0,0,0,0.5)';
ctx.fill();
推荐答案
在计算画布大小时,可以使用像素纵横比作为一个因素.
You can use pixel aspect ratio as a factor when calculating the canvas size.
var ratio = window.devicePixelRatio || 1;
var width = window.innerWidth * ratio;
var height = window.innerHeight * ratio;
canvas.width = width;
canvas.height = height;
CSS:
#canvasID {
position: fixed;
left: 0;
top: 0;
}
这篇关于javascript - Canvas 中的全屏矩形(Android/iOS 网络应用程序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:javascript - Canvas 中的全屏矩形(Android/iOS 网络应用程序)
基础教程推荐
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
