canvas屏幕适配可以用css样式自适应, 可以设置transform旋转角度和transfrom-origin:center以中心点旋转位置以及宽高width和height来实现对canvas的适应,这种适配可适合大部分游戏引擎(没做测试只是听说),但是对pixi却会导致事件响应错乱,css适应代码如下:
cssResize(){ let [canvas,stage] = [this.application.view,this.application.stage]; let [width,height] = [document.documentElement.clientWidth,document.documentElement.clientHeight]; let style = ""; if(width >= height){ style = `${width}px; height:${height}px; transform:rotate(0deg); transform-origin:center;`; } else{ style = `${height}px; height:${width}px; transform:rotate(90deg); transform-origin:${width/2}px ${width/2}px;`; } canvas.style = style; }
由于pixijs事件问题没有解决,故想方设法选择pixijs自适应的另一种解决方法:
以铺满宽或高为适配,计算出宽高比率,假如以宽度铺满为例,let ratio = canvas.width/clientWidth;height = canvas.height*ratio;下面是强制横屏的适配方法(注意这个是onresize的回调):
rendererResize(){ let stage = this.application.stage; let [width,height] = [document.documentElement.clientWidth,document.documentElement.clientHeight]; let ratio = 1; if(width > this.stageWidth || height > this.stageHeight){ width = this.stageWidth; height = this.stageHeight; } if(width >= height){ stage.rotation = 0; stage.x = 0; ratio = width/this.stageWidth; } else{ stage.rotation = Math.PI/2; stage.x = width; ratio = height/this.stageWidth; } this.application.view.style = `${width}px;height:${height}px;`; stage.scale.set(ratio); this.application.renderer.resize(width,height); }
旋转舞台,同时更改canvas的style.width和style.height,即可实现强制横屏。
这只是自己写的一个简单的适配。