2
votes

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();

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.

Solution:

based on answer by 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();
2

2 Answers

1
votes

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

You might try ensuring that your html and body elements are all the full width and height of the viewport. Include any ancestors between the canvas and body as well. See the following CSS code:

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