【发布时间】:2015-05-04 10:19:30
【问题描述】:
我在尝试使用 Canvas 在整个浏览器视口上渲染矩形时遇到问题。下面的代码在桌面上运行良好,但在移动设备上(在 iPad mini、Nexus 7 和 Galaxy S4 上测试),矩形只填满了屏幕的一部分(在 iPad 上大约是一半,在其他设备上是三分之二)。
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 的值是正确的。即使我使用硬编码值作为矩形的宽度/高度,我也会得到相同的结果。
解决方案:
基于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();
【问题讨论】:
标签: javascript canvas web html5-canvas