欢迎来到fullscreen API 噩梦。
此 API 仍在开发中,自从它首次在网络上发布以来,规范已经发生了很大变化。
不幸的是,截至今天,没有一个主流浏览器真正支持它(例如,实际规范建议使用 Promise),更糟糕的是,这些浏览器都没有为这个 API 使用相同的关键字。
所以让他们都满意可能有点苛刻。
但首先,您不应该听resize 事件,因为它可能会在全屏模式的激活/停用期间发生多次。
您需要的是fullscreenchange 事件。
幸运的是,每个 UA 都写了整个事件名称,其中没有任何驼峰式,但带有供应商前缀。 (并且由于某种原因,IE 不支持使用addEventListener 方法附加它...)
一旦你得到事件,为了知道我们是否真正进入或退出全屏模式,你必须检查document.[vendor-prefix]full(s||S)creenElement,如果有,那么我们进入了模式;否则我们退出它。
现在,要退出全屏模式,您必须调用
document.[vendor-prefix]((e||E)xit||Cancel)(f||F)ull(s||S)creen 方法。
所以这里有一个 dirty 辅助函数:
// if fullscreen API is supported it will return an array containing
// [vendor-prefix, 'full(s||S)creen', 'Exit||Cancel'];
var fs = function(){
// if it is natively supported without vendor prefix (may it happen some day...)
if('onfullscreenchange' in document){
return ['', 'Fullscreen', 'exit'];
}
if('onmozfullscreenchange' in document){
return ['moz','FullScreen', 'Cancel'];
}
if('onwebkitfullscreenchange' in document){
return ['webkit', 'Fullscreen', 'Exit'];
}
if('onmsfullscreenchange' in document){
return ['ms', 'Fullscreen', 'Exit'];
}
}();
if(fs){
// for some reason, IE doesn't support the addEventListener method...
document['on'+fs[0]+'fullscreenchange'] = function(){
ctx.clearRect(0, 0, c.width, c.height);
// check for 'fullscreenElement' to know weither we entered or exited the fullscreen mode
var status = document[fs[0]+fs[1]+'Element'];
var statusString = status ? 'entered':'exited';
ctx.fillText(statusString+' fullscreen', 250, 50);
// increment our fullscreen change counter
fs_count++;
if(status){
ctx.fillText('click the canvas to exit fullscreen mode', 150 , 100);
// attach the exit/cancel fullscreen call
c.onclick = function(){document[fs[0]+fs[2]+fs[1]]();};
}
// log the counters
ctx.fillText('fullscreen calls : '+fs_count, 0, 140);
ctx.fillText('resize calls : '+resize_count, 0, 150);
};
btn.onclick = function(){
//this one implies a new camelCase if a vendor prefix is needed...
var camel = fs[0] ? 'R':'r';
c[fs[0]+camel+'equest'+fs[1]]();
};
}
var ctx = c.getContext('2d');
ctx.fillStyle = "red";
var resize_count = 0;
var fs_count = 0;
// increment our resize counter
window.onresize= function(){resize_count++};
<canvas id="c" width="500"></canvas>
<button id="btn">enter fullscreen</button>
由于全屏请求在 iframe 中被阻止,您可以在操作中看到它here 并使用代码here
此外,您会注意到每个浏览器都会对这个请求采取不同的行动:webkit 浏览器将使页面全屏但保持元素的比例相同,而 FF 和 IE 将缩放元素以适应新的页面尺寸。
这意味着您不应查看getBoundingClientRect() rect,而应根据window.innerWidth 和window.innerHeight 属性计算新大小。