javascript - 全屏矩形在Canvas(Android / iOS网络应用程序) [英] javascript - Fullscreen rectangle in Canvas (Android/iOS web app)

查看:93
本文介绍了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();


推荐答案

画布大小。

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网络应用程序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆