Windows 8 Javascript设置画布以填充屏幕
我正在尝试使用Windows8/WinJS创建HTML5画布。以下是我所拥有的:Windows 8 Javascript设置画布以填充屏幕,javascript,html5-canvas,windows-store-apps,winjs,Javascript,Html5 Canvas,Windows Store Apps,Winjs,我正在尝试使用Windows8/WinJS创建HTML5画布。以下是我所拥有的: var body = document.getElementById("body"); var canvas = document.createElement("canvas"); canvas.id = "myCanvas"; body.appendChild(canvas); var canvasContext = canvas.getContext("2d");
var body = document.getElementById("body");
var canvas = document.createElement("canvas");
canvas.id = "myCanvas";
body.appendChild(canvas);
var canvasContext = canvas.getContext("2d");
canvas.width = document.width;
canvas.height = document.height;
canvasContext.fillStyle = "#f00";
canvasContext.fillRect(canvas.width - 100, canvas.height - 50, 100, 50);
console.log("canvas width " + canvas.width + ", height " + canvas.height);
大部分内容直接来自教程,但对于我所看到的所有教程,宽度和高度都设置为硬编码数字,例如:
canvas.width = 800;
canvas.height = 600;
诚然,这确实有效,但我希望画布与屏幕一样大,无论分辨率如何。如何实现这一点?所说的“屏幕”,是指浏览器窗口的大小吗
如果是,则可以使用window.outerWidth和window.outerHeight,而不是document.width和document.height。或者如果使用jQuery:$(window.width()和$(window.height())
此外,您还需要侦听窗口上的“调整大小”事件,以便在调整浏览器大小时可以重新初始化画布。您可以使用视口和视口高度CSS值来执行此操作(请参阅有关这些值的一些信息) 在这种特定情况下,您只需执行以下操作:
canvas.style.width = "100vw";
canvas.style.height = "100vh";
此解决方案的优点是,您不必加载第三方库,例如JQuery,使其大小达到全宽/全高。这是一个windows应用商店应用程序-因此没有浏览器。尽管如此,这是完美的