【问题标题】:javascript - Fullscreen rectangle in Canvas (Android/iOS web app)javascript - Canvas 中的全屏矩形(Android/iOS 网络应用程序)
【发布时间】: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


    【解决方案1】:

    在计算画布大小时,您可以使用像素纵横比作为一个因素。

    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;
        }
    

    【讨论】:

    • 谢谢,这成功了!但是,我不得不稍微修改您的解决方案,因为您发布的内容并没有完全按照应有的方式工作。 CSS 被证明是不必要的,我只使用了代码的前三行,使用计算出的宽度和高度来绘制矩形(工作代码现在在我的原始帖子中)。
    【解决方案2】:

    您可以尝试确保您的htmlbody 元素都是视口的全部宽度和高度。包括canvasbody 之间的任何祖先。请参阅以下 CSS 代码:

    html,
    body {
      width: 100%;
      height: 100%;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-12-07
      • 2013-01-05
      • 2012-12-14
      • 2016-06-02
      • 2012-03-17
      • 2014-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多