preface

Phaser is an open source 2D game framework. During phaser development, have you ever thought about how to make a similar adaptation to VW on the mobile end? During phaser development, you can directly build the UI according to the coordinates and dimensions of the design draft

See my nuggets article: Mobile VW Adaptation from an Ancestral project

Is beginning to the end

Take a look at the final effect of the adaptation scheme. The following is the effect of the same set of code on the phone and pad

Schematic diagram, this is the general standard design draft size, iPhone 678, 375×667

This is an analog iPhoneX minus the bangs, 375×812

This is the portrait iPad mini, 768×1024

This is the landscape iPad Mini, 1024×768

When developing, we add an element, set its coordinates to (0, 0), and if its origin is also (0, 0), its upper left corner is in the upper left corner of the area inside the blue box

The core concept

1. Content area: the area in the blue box in the figure above is the main interactive content UI display area

2. Background area: the area in the red box in the figure above, where non-main interactive content UI such as background and return button are placed

Viewport: The visible area of the screen

Adaptation Scheme Summary

1. If the screen is narrow, zoom in and out by the width of the screen / 375 and center the screen vertically up and down

2. If the screen is widescreen, zoom in at the height of the screen / 667 and center the left and right horizontally

The main code

show code

// Camera zoom ratio
let zoom: nubmer = 1
// The top left x-coordinate of the background area after scaling
let backgroundRectX: nubmer = 0
// The top left Y coordinate of the background area after scaling
let backgroundRectY: nubmer = 0
const designWidth: nubmer = 375
const designHeight: nubmer = 667
const designRatio: nubmer = designWidth / designHeight
const viewRatio: nubmer = window.innerWidth / window.innerHeight
// Determine the base of zoom according to the aspect ratio of the design draft and the aspect ratio of the viewport
if (designRatio > viewRatio) {
  // Scale based on width
  zoom = window.innerWidth / this.designWidth
  backgroundRectY = -(window.innerHeight / zoom - designHeight) / 2
} else {
// Scale based on height
  zoom = window.innerHeight / designHeight
  backgroundRectX = -(window.innerWidth / zoom - designWidth) / 2
}
const camera: Phaser.Cameras.Scene2D.Camera = this.cameras.main
// Camera zoom
cameras.setZoom(zoom)
// The camera moves
camerassetScroll(-(window.innerWidth - designWidth) / 2, -window.innerHeight - designHeight) / 2)
Copy the code