问题描述:
因为canvas画布的高度和宽度是一开始固定写好的,当需要全屏时,画布 的高度是开始定义的高度,就会出现屏幕下方黑了一块,如下图,所以我们需要判断是否全屏,画布根据这个属性改变画布高度。

1.绑定resize事件,当浏览器窗口大小发生变化时判断是否全屏
created() {
this.isFullScreen = this.isFullscreen();
window.addEventListener('resize', () => {
this.isFullScreen = this.isFullscreen();
});
},
2.首先浏览器是否支持全屏,如果支持全屏继续
3.调整一下缩放比,全屏时缩放比为1
methods: {
// 进入全屏
fullScreen(index) {
if (this.isFullscreenEnabled()) {
return this.$message('该浏览器不支持全屏');
}
this.dpr = this.getRatio() / 100;
if (this.dpr !== 1) { // 如果进行了缩放
document.getElementsByTagName('body')[0].style.zoom = 1; // 就去修改页面的缩放比例为1
}
const element = document.querySelector(`.work-item-${index}`); // 全屏的dom节点
// 兼容不同浏览器全屏
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullscreen();
}
},
// 退出全屏
exitScreen() {
// 兼容不同浏览器退出全屏
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
},
// 获取当前浏览器屏幕的dpr
getRatio() {
let ratio = 0;
const { screen } = window;
const ua = navigator.userAgent.toLowerCase();
if (window.devicePixelRatio !== undefined) {
ratio = window.devicePixelRatio;
/* eslint no-bitwise: ["error", { "allow": ["~"] }] */
} else if (~ua.indexOf('msie')) {
if (screen.deviceXDPI && screen.logicalXDPI) {
ratio = screen.deviceXDPI / screen.logicalXDPI;
}
} else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
ratio = window.outerWidth / window.innerWidth;
}
if (ratio) {
ratio = Math.round(ratio);
}
return ratio;
},
// 浏览器是否支持全屏
isFullscreenEnabled() {
return document.fullscreenEnabled
|| document.mozFullScreenEnabled
|| document.webkitFullscreenEnabled
|| document.msFullscreenEnabled || false;
},
// 判断是否全屏
isFullscreen() {
return Boolean(document.fullscreenElement
|| document.msFullscreenElement
|| document.mozFullScreenElement
|| document.webkitFullscreenElement || false);
},
}
4.canvas绘图进入全屏需要从父组件接收一个是否全屏的属性,然后定义canvas的高度和宽度,这样就能达到canvas全屏效果了
const container = document.getElementById(this.container);
container.innerHTML = '';
const width = container.scrollWidth || 500;
let height = 500;
if (this.isFullScreen) {
// 全屏时获取浏览器高度和画布上方头部div的高度,计算得到画布高度
height = window.screen.height - document.querySelector('.canvas-header').offsetHeight;
}

本文讲述了如何处理浏览器全屏时canvas画布高度不足导致底部出现黑边的问题。通过监听resize事件和判断全屏状态,动态调整canvas的高度以适应全屏显示,并介绍了全屏操作的浏览器兼容性处理。同时,提到了缩放比例的调整,确保全屏时画布尺寸正确。

被折叠的 条评论
为什么被折叠?



