Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Summarize the front-end knowledge in the 50-tone Mini Game.

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "summing up the front-end knowledge of the 50-tone Mini Game". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Realize

The implementation effect is as follows, the application is mainly divided into three pages:

Home page: including menu options (hiragana exercise, katakana exercise, mixed exercise), dark mode toggle button.

Answer page: including the remaining opportunities and score display area, the middle question area, the bottom answer button.

Results page: results score display and return home button.

The answer logic rule is to select which word in the question display area corresponds to the correct option from the four answer buttons given, and to score the feedback according to the click of the error. After 10 errors, the game ends and loads the results page. The implementation of game logic is not the main content of this article, so I will not repeat it later. The follow-up content of this paper is the introduction of the front-end knowledge involved in the Mini Game development process.

Dark mode ⚪⚫

With the introduction of dark mode in Windows 10, MacOs, Android and other systems, browsers also begin to support the detection of system theme color configuration, and more and more web applications are equipped with dark mode switching function. In order to optimize the visual experience of 50-tone Mini Game, I have also configured a dark style, and the results are as follows:

CSS Media query to determine Dark Mode

The prefers-color-scheme media feature is used to detect whether the user has set the system's theme color to light or dark. The usage syntax is as follows:

@ media (prefers-color-scheme: value) {} where value has the following three values, of which:

Light: indicates that the user system supports dark mode and has been set to a light theme (the default).

Dark: indicates that the user system supports dark mode and has been set to a dark theme.

No-preference: indicates that the user system does not support dark mode or does not know whether it is set to dark mode (deprecated).

If the result is no-preference, it is impossible to know through this media feature whether the host system supports setting a theme color, or whether the user actively sets it to no preference. For privacy reasons, users or user agents may also set it to no-preference inside the browser in some cases.

In the following example, the background color of the .demo element is # FFFFFF; when the system theme color is dark, and the background color of the .demo element is # 000000 when the system theme color is light.

@ media (prefers-color-scheme: dark) {.demo {background: # FFFFFF;}} @ media (prefers-color-scheme: light) {.demo {background: # 0000000;}}

JavaScript judges dark mode

The window.matchMedia () method returns a new MediaQueryList object that represents the parsed result of the specified media query (en-US) string. The returned MediaQueryList can be used to determine whether the Document matches the media query, or to monitor a document to determine whether it matches or stops matching the media query. Where the MediaQueryList object has properties matches and media, and methods addListener and removeListener.

Using matchMedia as a judgment medium, you can also identify whether the system supports theme colors:

If (window.matchMedia ('(prefers-color-scheme)'). Media = = 'not all') {/ / browser does not support theme color settings} if (window.matchMedia (' (prefers-color-scheme: dark)') .colors) {/ / dark mode} else {/ / light mode}

In addition, you can dynamically monitor the status of the dark mode of the system and make a real-time response according to the switching of the dark mode of the system:

Window.matchMedia ('(prefers-color-scheme: dark)') .addListener (e = > {if (e.matches) {/ / enable dark mode} else {/ / turn off dark mode})

Or detect dark or light modes separately:

Const listeners = {dark: (mediaQueryList) = > {if (mediaQueryList.matches) {/ / enable dark mode}}, light: (mediaQueryList) = > {if (mediaQueryList.matches) {/ / enable light mode}; window.matchMedia ('(prefers-color-scheme: dark)') .addListener (listeners.dark); window.matchMedia ('(prefers-color-scheme: light)') .addListener (listeners.light)

In the 50-tone Mini Game, it uses JavaScript to detect whether the system turns on the dark mode, dynamically adds the css class name to automatically load the dark mode, and also provides a light and dark color toggle button, which can switch the theme manually.

Judging dark mode in HTML element

When the page uses picture elements, you can directly determine whether the system is in dark mode in HTML. Such as:

The picture element allows us to display different images on different devices, which is generally used in response mode. HTML5 introduces an element that makes the adjustment of image resources more flexible. Element zero or more elements and a

Element, each element matches a different device and references a different image source, and if there is no match, select

The url in the src attribute of the element.

Note:

The element is placed after the last element, and is displayed if the browser does not support the attribute

A picture of the element.

Offline caching

In order to be able to generate shortcuts for quick access on the desktop like native applications and use them offline anytime, anywhere, 50 tone Mini Game uses offline caching technology, which is a PWA application. The following is a brief description of the implementation technology of PWA offline applications.

PWA (progressing web app), a progressive web application, is the next generation WEB application model. A PWA application is first of all a web page, and with the help of App Manifest and Service Worker to achieve installation and offline functions.

Features:

Progressive: suitable for all users who choose any browser, because it is developed with progressive enhancement as its core purpose.

Adaptive: suitable for any model: desktop, mobile, tablet or any future device.

Connection independence: the ability to work offline or in a low-quality network with the help of service worker threads.

Offline push: the use of push message notification allows our application to enhance the user experience like Native App. Timely update: keep up-to-date with the update process of the service worker thread at all times.

Security: provided through HTTPS to prevent snooping and ensure that the content is not tampered with.

Configure page parameters

Add a file manifest.webmanifest or manifest.json file to the root directory of the project, and write the following configuration information in the file. In this example, the page parameter information of 50-tone Mini Game is configured as follows:

/ / manifest.webmainifest {"name": "description", "short_name": "standalone", "start_url": "index.html", "display": "standalone", "background_color": "# fff", "description": "excuse me", "icons": [{"src": "assets/images/icon-64x64.jpg", "sizes": "64x64" "type": "image/jpg"}, {"src": "assets/images/icon-256x256.jpg", "sizes": "256x256", "type": "image/jpg"]}

Parameter description:

The name of the name:Web App, which is also the name of the application icon when it is saved to the desktop.

If short_name:name is too long, short_name will be used instead of name display, which is the abbreviation of Web App.

Start_url: specifies that the URL is loaded when the user opens the Web App. The URL is relative to the path where the manifest file is located.

Display: specifies the display mode for the application, which has four values to choose from:

Fullscreen: full screen display, which will fill up all the display areas as much as possible.

Standalone: browser-related UI (such as navigation bar, toolbar, etc.) will be hidden to look more like a Native App.

Minimal-ui: the display is similar to standalone, where the browser-related UI is minimized to a button, and the implementation varies slightly from browser to browser. Browser: generally speaking, it is consistent with the normal style of opening it with a browser.

It should be noted that when some system browsers do not support fullscreen, it will be displayed as standalone effect, when standalone is not supported, it will be displayed as minimal-ui effect, and so on.

Description: application description.

Icons: specifies the desktop icon and startup page image of the application, represented by an array:

Sizes: icon size. By specifying the size, the system will select the most appropriate icon to display in the appropriate location.

Src: icon path. Relative paths are relative to manifest files, or absolute paths can be used.

Type: icon picture type. The browser will select the image closest to 128dp (px = dp * (dpi / 160)) from icons as the startup screen image.

Background_color: specify the background color of the startup screen. The same color can be used to achieve a smooth transition from the startup screen to the home page, and can also be used to improve the user experience when the page resources are loaded.

Theme_color: specifies the theme color of the Web App. You can use this property to control the color of the browser UI. For example, the color of the status bar, the status bar and the address bar in the content page.

Automatic generation tool of configuration information: https://tomitm.github.io/appmanifest/

Configure the HTML file

Introduce the manifest configuration file into index.html and add the following configuration information to head to be compatible with the iOS system

I don't know what to do.

Apple-touch-icon: specifies the application icon, which is similar to the icons configuration of the manifest.json file, and also supports the sizes attribute for selection in different scenarios.

Apple-mobile-web-app-capable: similar to display in manifest.json, you can enter standalone mode by setting it to yes.

Apple-mobile-web-app-title: specifies the name of the application.

Apple-mobile-web-app-status-bar-style: specifies the style of the status bar status bar of the iOS mobile device, which can be set by Default,Black,Black-translucent.

Register to use Service Worker

Add the following code to index.html for server-worker registration:

Window.addEventListener ('load', () = > {registerSW ();}); async function registerSW () {if (' serviceWorker' in navigator) {try {await navigator.serviceWorker.register ('. / sw.js');} catch (e) {console.log (`SW registration failed`);}

Use serviceWorkerContainer.register () for Service worker registration while adding try...catch... Fault tolerant judgment to ensure normal operation when Service worker is not supported. It is also important to note that there are serviceWorker objects in navigator only under https.

Service workers essentially acts as a proxy server between Web applications, browsers, and the network (when available). Designed to create an effective offline experience, it intercepts network requests and updates resources from the server based on whether the network is available to take appropriate action. It also provides an entrance to push notifications and access the background synchronization API. To learn more about Service workder, you can visit the link at the end of the article.

Add sw.js to the root directory to define cache information and methods

/ / define the cached key value const cacheName = 'kana-v1';// define the file to be cached const staticAssets = ['. /','. / index.html','. / assets/css/main.css','. / assets/js/main.js','. / assets/images/bg.jpg' / /.] / / listen for install events. After installation, perform file cache self.addEventListener ('install', async e = > {/ / find the cache corresponding to key and get the operable cache object const cache = await caches.open (cacheName); / / add the files that need to be cached to await cache.addAll (staticAssets); return self.skipWaiting ();}) / / listen for activate events to update cached data self.addEventListener ('activate', e = > {/ / ensure that fetch triggers self.clients.claim ();}); / / listen for fetch events to use cached data: self.addEventListener (' fetch', async e = > {const req = e.request; const url = new URL (req.url); if (url.origin = location.origin) {e.respondWith (cacheFirst (req) } else {e.respondWith (networkAndCache (req));}}); async function cacheFirst (req) {/ / determine whether the current request needs cache const cache = await caches.open (cacheName); const cached = await cache.match (req); / / use cache if there is cache, and get return cached from new request if there is no cache | | fetch (req);} async function networkAndCache (req) {const cache = await caches.open (cacheName) Try {/ / cache error also gets const fresh = await fetch (req); await cache.put (req, fresh.clone ()); return fresh;} catch (e) {const cached = await cache.match (req); return cached;}} directly from the new request.

The standard web worker programming approach used in sw.js uses self.addEventListener () because it runs in another global context (self), which is different from window.

Cache API is the interface provided by Service Worker to operate cache. These interfaces are based on Promise implementation, including Cache and CacheStorage. Cache directly deals with requests and provides storage mechanism for cached Request / Response object pairs. CacheStorage represents the storage instance of Cache object. We can access Cache API directly using the global caches attribute.

* * description of API related to Cache:

Cache.match (request, options): returns a Promise object, and the result of resolve is the first cached request that matches the Cache object.

Cache.matchAll (request, options): returns a Promise object, and the result of resolve is an array of all requests that match the Cache object. Cache.addAll (requests): receives an array of URL, retrieves and adds the returned response object to the given Cache object.

Cache.delete (request, options): searches for Cache entries with a key value of request. If found, delete the Cache entry and return a Promise object with resolve as true; if not, return a Promise object with resolve as false

Cache.keys (request, options): returns a Promise object, and the result of resolve is an array of key values of the Cache object.

Note: request.clone () and response.clone () are used because request and response are a stream and can only be consumed once. Caching has already been consumed once, and it will take another time to initiate a HTTP request, at this point, use the clone method to clone the request.

At this point, when the installed Service Worker page is opened, the Service Worker script update is triggered. The Service Worker script update is triggered when the last time the script updated the timestamp written to the Service Worker database and the current update takes more than 24 hours. When the sw.js file changes, the Service Worker script update is triggered. The update process is similar to installation, except that the updated Service Worker will not enter the active state immediately after the installation of the update. The updated Service Worker will co-exist with the original Service Worker and run its install. Once the new Service Worker is successfully installed, it will enter the wait state and need to wait for the old version of Service Worker to enter / thread to terminate.

For more advanced knowledge of Server Worker, please see the link at the end of the article.

Achieve results:

On the PC side? ️: Windows, there will be an installation prompt after opening the application for the first time in the browser. Click the installation icon to install it. Application shortcuts will be generated in the desktop and start menu. Click the shortcut to open the application.

Mac?: the browsers of the chromiumn kernel above (chrome, opera, the new version of edge) are similar. Shortcuts are generated in launchpad after installation.

Mobile?: iPhone. Select Save to Desktop in the browser, you can generate a desktop icon, and click the icon to open the offline application.

Cherry blossom falling animation?

In order to enhance the visual effect and interest, cherry blossoms are added to the page. The effect of falling. The Element.animate () method is mainly used in the animation of falling effects.

Element's animate () method is a convenient way to create a new Animation, apply it to an element, and then run the animation. It will return a new instance of the Animation object. Multiple animation effects can be applied to an element. You can get a list of these animation effects by calling this function: Element.getAnimations ().

Basic syntax:

Var animation = element.animate (keyframes, options)

Parameters:

Keyframes: Keyframe. An object that represents a collection of keyframes.

Options: optionally a shaping number (in milliseconds) that represents the duration of the animation, or an object that contains one or more time attributes:

Id: optional attribute that can be uniquely identified in animate (): a string (DOMString) delay used to reference the animation: optional, delay milliseconds for the start time, the default is 0.

Direction: optional, the direction of motion of the animation. Run normal forward, run reverse backward, switch direction alternate after each iteration, run backward, and switch direction alternate-reverse after each iteration. The default is normal.

Duration: optionally, the number of milliseconds for each iteration of the animation. The default is 0. Easing: optional, the frequency with which the animation changes over time. Accept preset values including linear, ease, ease-in, ease-out, ease-in-out, and a custom value cubic-bezier, such as cubic-bezier (0.42,0,0.58,1). The default is linear.

EndDelay: optional, a delay after the end of the animation. The default value is 0.

Fill: optional, to define the timing of the influence of animation effects on elements, including the impact on elements before the start of backwards animation, the impact on elements after the completion of forwards animation, and both both. The default is none.

IterationStart: optionally, describe at which point in the iteration the animation should begin. For example, 0.5 means that it starts in the middle of the first iteration, and when this value is set, the animation with 2 iterations will end in the middle of the third iteration. The default is 0.0.

Iterations: optional, the number of times the animation should be repeated. The default is 1, or you can take the value of infinity so that it repeats when the element exists.

The following code is the specific implementation of this example, HTML has a number of .petal elements, and then JavaScript gets all .petal elements to add random animation, css adds two kinds of rotation and deformation animation to achieve the effect of cherry petals falling.

Var petalPlayers = []; function animatePetals () {var petals = document.querySelectorAll ('.petal'); if (! petals [0] .animate) {var petalsContainer = document.getElementById ('petals_container'); return false;} for (var I = 0, len = petals.length; I)

< len; ++i) { var petal = petals[i]; petal[xss_clean] = '

'; var scale = Math.random () * .6 + .2 Var player = petal.animate ([{transform: 'translate3d (' + (I / len * 100) + 'vw,0,0) scale (' + scale +'), opacity: scale}, {transform: 'translate3d (' + (I / len * 100 + 10) + 'vw,150vh,0) scale (' + scale +')', opacity: 1}] {duration: Math.random () * 90000 + 8000, iterations: Infinity, delay:-(Math.random () * 5000)}) PetalPlayers.push (player);}} animatePetals (); .animation: driftyRotate 1s infinite both ease-in-out; perspective: 1000;} .petal .askew {transform: skewY (10deg); display: block; animation: drifty 1s infinite alternate both ease-in-out; perspective: 1000;} .petal: nth-of-type (7n) .askew {animation-delay:-.6s; animation-duration: 2.25s } .petal: nth-of-type (7n + 1) .askew {animation-delay:-.879s; animation-duration: 3.5s;} / *. * / .petal:nth-of-type (9n). Nth-of-type {animation-duration: 2s;} .petal: nth-of-type (9n + 1). } / *. * / @ keyframes drifty {0% {transform: skewY (10deg) translate3d (- 250%, 0,0); display: block;} 100% {transform: skewY (- 12deg) translate3d (250%, 0,0); display: block;}} @ keyframes driftyRotate {0% {transform: rotateX (0); display: block;} 100% {transform: rotateX (359deg); display: block;}}

For the complete code, please see the link after the article.

CSS judges the horizontal screen of the phone.

In this example, the 50-tone Mini Game application is developed for the mobile end and has not adapted to the style of the PC, so you can add a horizontal guide page to prompt the user to use the vertical screen. To judge whether the mobile device is in the horizontal screen state in CSS, we need to use aspect-ratio for media query, and judge by testing the aspect ratio of viewport.

The aspect-ratio aspect ratio property is specified as a value to represent the aspect ratio of the viewport. It is a range, and you can query the minimum and maximum values using min-aspect-ratio and max-aspect-ratio, respectively. The basic syntax is as follows:

/ * minimum aspect ratio * / @ media (min-aspect-ratio: 8ax 5) {/ /...} / * maximum aspect ratio * / @ media (max-aspect-ratio: 3Univer 2) {/ /...} / * an explicit aspect ratio is placed at the bottom to prevent coverage * / @ media (aspect-ratio: 1can1) when conditions are met at the same time.

The specific implementation in the application is to add a .mod _ orient_layer guide layer and hide it, and display it when the minimum aspect ratio is reached:

.mod _ orient_layer {display: none; position: fixed; height: 100%; width: 100%; left: 0; top: 0; right: 0; bottom: 0; z-index: 999; background: # FFFFFF url ('landscape.jpg') no-repeat center; background-size: auto 100%;} @ media screen and (min-aspect-ratio: 13 landscape.jpg' 8) {.mod _ orient_layer {display: block;}}

Achieve results:

Compatibility

The following is a compatibility view of several properties covered in this article, and compatibility adaptation should be paid attention to in actual production projects.

Photoshop skill

Logo design

Logo is mainly composed of two elements: a ⛩️icon and the Japanese hiragana ⛩️, both of which are classic Japanese elements. At the same time, it stretches and gradients to form a shadow similar to ⛩️, so that letters and graphics are cleverly connected together to make the picture harmonious. The logo background color uses the application theme background color to establish an invisible relationship with the page to form a unified style standard for the whole link. I can't make it up any more. ?

This is the end of the content of "summing up the front-end knowledge in the 50-tone Mini Game". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report