It turned out that I knew nothing about a lot of Web apis, which opened the door to my new world. In the future, Web can do more. Let’s rule as soon as possible, Ho ho ho.
Although many of these apis still have compatibility issues, it is important to know that I have tested all the code in this article. I hope you get something out of it.
Blog. Bitsrc. IO /10-useful…
You probably already know and use the more popular Web APIs (Web Worker, Fetch, etc.), but there are a few less popular APIs that I personally like to use and recommend you try them too.
All of the Web API examples described in this article can be found here:
1. Web Audio API
Web Audio API MDN
The Web Audio API allows you to manipulate Audio streams on the Web. It can be used to add effects and filters to audio sources on the network.
Audio sources can come from
Let’s look at a simple example:
<body>
<header>
<h2>Web APIs<h2>
</header>
<div class="web-api-cnt">
<div class="web-api-card">
<div class="web-api-card-head"> Demo - Audio </div>
<div class="web-api-card-body">
<div id="error" class="close"></div>
<div>
<audio controls src="./lovely.mp4" id="audio"></audio>
</div>
<div>
<button onclick="audioFromAudioFile.init()">Init</button>
<button onclick="audioFromAudioFile.play()">Play</button>
<button onclick="audioFromAudioFile.pause()">Pause</button>
<button onclick="audioFromAudioFile.stop()">Stop</button>
</div>
<div>
<span>Vol: <input onchange="audioFromAudioFile.changeVolume()" type="range" id="vol" min="1" max="3"
step="0.01" value="1" /></span>
<span>Pan: <input onchange="audioFromAudioFile.changePan()" type="range" id="panner" min="1"
max="1" step="0.01" value="0" /></span>
</div>
</div>
</div>
</div>
</body>
<script>
const l = console.log
let audioFromAudioFile = (function () {
var audioContext
var volNode
var pannerNode
var mediaSource
function init() {
l("Init")
try {
audioContext = new AudioContext()
mediaSource = audioContext.createMediaElementSource(audio)
volNode = audioContext.createGain()
volNode.gain.value = 1
pannerNode = new StereoPannerNode(audioContext, { pan: 0 })
mediaSource.connect(volNode).connect(pannerNode).connect(audioContext.destination)
console.log(volNode)
}
catch (e) {
error.innerHTML = "The Web Audio API is not supported in this device."
error.classList.remove("close")}}function play() {
audio.play()
}
function pause() {
audio.pause()
}
function stop() {
audio.stop()
}
function changeVolume() {
volNode.gain.value = document.getElementById('vol').value
}
function changePan() {
pannerNode.gain.value = tdocument.getElementById('panner').value
}
return {
init,
play,
pause,
stop,
changePan,
changeVolume
}
})()
</script>
Copy the code
Translator’s note: there is a small problem with the source code, I have modified the above code, it works, but the MP4 file is changed to my own.
This example passes audio from the < Audio > element to the AudioContext. Sound effects (such as audio images) are added to the audio source before they are added to the audio output (speakers).
Clicking the Init button invokes the Init function. This will create an AudioContext instance and set it to AudioContext. Next, it creates a media source, createMediaElementSource(Audio), passing the audio elements as the audio source.
CreateGain Creates the volume node volNode. Here, we adjust the volume of the audio. Next, use StereoPannerNode to set up the audio and video effects. Finally, connect the node to the media source.
We have a slider for volume and audio. Dragging them affects the volume and audio.
There is a problem with this example, so the link does not work either. You can copy the above code and run it locally
try it
2. Fullscreen API
Fullscreen API MDN
The Fullscreen API enables us to enable full-screen mode in our Web app. It allows you to select the elements to view in full screen mode. In Android phones, it will remove the browser window and the status bar at the top of Android (where network status, battery status, etc.).
Methods:
-
RequestFullscreen displays selected elements in full-screen mode on the system, closing other applications as well as browser and system UI elements.
-
ExitFullscreen Returns the full-screen mode to normal.
Let’s look at a simple example where we can watch a video in full screen mode:
<body>
<header>
<h2>Web APIs<h2>
</header>
<div class="web-api-cnt">
<div class="web-api-card">
<div class="web-api-card-head"> Demo - Fullscreen </div>
<div class="web-api-card-body">
<div id="error" class="close"></div>
<div> This API makes fullscreen-mode of our webpage possible. It lets you select the Element you want to
view in fullscreen-mode, then it shuts off the browsers window features like URL bar, the window
pane, and presents the Element to take the entire width and height of the system. In Android phones,
it will remove the browsers window and the Android UI where the network status, battery status are
displayed, and display the Element in full width of the Android system. </div>
<div class="video-stage">
<video id="video" src="./lovely.mp4"></video>
<button onclick="toggle()">Toogle Fullscreen</button>
</div>
<div> This API makes fullscreen-mode of our webpage possible. It lets you select the Element you want to
view in fullscreen-mode, then it shuts off the browsers window features like URL bar, the window
pane, and presents the Element to take the entire width and height of the system. In Android phones,
it will remove the browsers window and the Android UI where the network status, battery status are
displayed, and display the Element in full width of the Android system. </div>
</div>
</div>
</div>
</body>
<script>
const l = console.log
function toggle() {
const videoStageEl = document.querySelector(".video-stage")
console.log(videoStageEl.requestFullscreen)
if (videoStageEl.requestFullscreen) {
if (!document.fullscreenElement) {
videoStageEl.requestFullscreen()
}
else {
document.exitFullscreen()
}
} else {
error.innerHTML = "Fullscreen API not supported in this device."
error.classList.remove("close")}}</script>
Copy the code
The video element is in the div# video-stage element and has a button Toggle Fullscreen.
When we click the Toggle Fullscreen button, we want to make the element div#video-stage Fullscreen.
Take a look at the toggle function:
function toggle() {
const videoStageEl = document.querySelector(".video-stage")
if(!document.fullscreenElement)
videoStageEl.requestFullscreen()
else
document.exitFullscreen()
}
Copy the code
Get the div#video-stage element and keep the example on videoStageEl.
We used document. FullsreenElement properties can know whether the element is in full screen mode, if not full screen mode, you can call on videoStageEl requestFullscreen () method, Make div#video-stage take over the entire device view.
If you click the Toggle Fullscreen button in full-screen mode, document.exitFullcreen() is called to return to the normal view.
try it
Note: the video resources in this link can not be found, but the full screen function is normal, you can also test locally
3. Web Speech API
Web Speech API MDN
The Web Speech API allows you to add Speech synthesis and Speech recognition capabilities to Web applications.
Using this API, you will be able to issue voice commands to Web applications, just as you can on Android with Google Speech or on Windows with Cortana.
Let’s look at a simple example. We’ll see how to implement text-to-speech and speech-to-text transformations using the Web Speech API.
<body>
<header>
<h2>Web APIs<h2>
</header>
<div class="web-api-cnt">
<div id="error" class="close"></div>
<div class="web-api-card">
<div class="web-api-card-head"> Demo - Text to Speech </div>
<div class="web-api-card-body">
<div>
<input placeholder="Enter text here" type="text" id="textToSpeech" />
</div>
<div>
<button onclick="speak()">Tap to Speak</button>
</div>
</div>
</div>
<div class="web-api-card">
<div class="web-api-card-head"> Demo - Speech to Text </div>
<div class="web-api-card-body">
<div>
<textarea placeholder="Text will appear here when you start speeaking."
id="speechToText"></textarea>
</div>
<div>
<button onclick="tapToSpeak()">Tap and Speak into Mic</button>
</div>
</div>
</div>
</div>
</body>
<script>
try {
var speech = new SpeechSynthesisUtterance()
var recognition = new SpeechRecognition()
} catch (e) {
error.innerHTML = "Web Speech API not supported in this device."
error.classList.remove("close")}function speak() {
speech.text = textToSpeech.value
speech.volume = 1
speech.rate = 1
speech.pitch = 1
alert(window.speechSynthesis)
window.speechSynthesis.speak(speech)
}
function tapToSpeak() {
recognition.onstart = function () { }
recognition.onresult = function (event) {
const curr = event.resultIndex
const transcript = event.results[curr][0].transcript
speechToText.value = transcript
}
recognition.onerror = function (ev) {
console.error(ev)
}
recognition.start()
}
</script>
Copy the code
The first Demo, Demo-Text to Speech, demonstrates the ability to receive input Text through a simple input box and output Speech after a button is clicked.
Take a look at the speak function:
function speak() {
speech.text = textToSpeech.value
speech.volume = 1
speech.rate = 1
speech.pitch = 1
window.speechSynthesis.speak(speech)
}
Copy the code
It instantiates the SpeechSynthesisUtterance() object, converting the text we enter in the input box to speech. Then, call the Speak function of the speech object SpeechSynthesis to release the text from the input box into our speaker.
The second Demo – Demo-Speech to Text is a Speech recognition Demo. We click the Tap and Speak into Mic button, Speak into the microphone, and the words we say are translated into text.
Tap and Speak into Mic call the tapToSpeak function after clicking:
function tapToSpeak() {
recognition.onstart = function () { }
recognition.onresult = function (event) {
const curr = event.resultIndex
const transcript = event.results[curr][0].transcript
speechToText.value = transcript
}
recognition.onerror = function (ev) {
console.error(ev)
}
recognition.start()
}
Copy the code
Simple, instantiate SpeechRecognition, then register event handlers and callbacks. Onstart is called when speech recognition starts and onError when an error occurs. Onresult is called every time speech recognition catches a line.
As you can see, in the onResult callback, we extract the text and set it to the text area. So when we speak into the microphone, it’s printed in the text area.
try it
Translator: Neither my phone nor my computer Chrome(V83) supports this API.
4. Bluetooth API
Bluetooth API MDN
The experiment technology
The Bluetooth API makes it possible to access a low-power Bluetooth device on a phone and use it to share data from a Web page to another device.
Imagine being able to create a Web chat application that can send and receive messages from other phones over Bluetooth.
Basic API is the navigator. Bluetooth. RequestDevice. Calling it will cause the browser to prompt the user to select a device, allowing them to select a device or cancel the request.
The navigator. Bluetooth. RequestDevice needs an object. This object defines the filter used to return the Bluetooth device that matches the filter.
Let’s look at a simple demonstration. This presentation will use the navigator. Bluetooth. RequestDeviceAPI from BLE devices retrieve basic information.
<body>
<header>
<h2>Web APIs<h2>
</header>
<div class="web-api-cnt">
<div class="web-api-card">
<div class="web-api-card-head"> Demo - Bluetooth </div>
<div class="web-api-card-body">
<div id="error" class="close"></div>
<div>
<div>Device Name: <span id="dname"></span></div>
<div>Device ID: <span id="did"></span></div>
<div>Device Connected: <span id="dconnected"></span></div>
</div>
<div>
<button onclick="bluetoothAction()">Get BLE Device</button>
</div>
</div>
</div>
</div>
</body>
<script>
function bluetoothAction() {
if (navigator.bluetooth) {
navigator.bluetooth.requestDevice({
acceptAllDevices: true
}).then(device= > {
dname.innerHTML = device.name
did.innerHTML = device.id
dconnected.innerHTML = device.connected
}).catch(err= > {
error.innerHTML = "Oh my!! Something went wrong."
error.classList.remove("close")})}else {
error.innerHTML = "Bluetooth is not supported."
error.classList.remove("close")}}</script>
Copy the code
The device information will be displayed. Click the Get BLE Device button to invoke the bluetoothAction function.
function bluetoothAction() {
if (navigator.bluetooth) {
navigator.bluetooth.requestDevice({
acceptAllDevices: true
}).then(device= > {
dname.innerHTML = device.name
did.innerHTML = device.id
dconnected.innerHTML = device.connected
}).catch(err= > {
error.innerHTML = "Oh my!! Something went wrong."
error.classList.remove("close")})}else {
error.innerHTML = "Bluetooth is not supported."
error.classList.remove("close")}}Copy the code
The bluetoothAction function calls the navigator. Bluetooth. RequestDevice API, parameter is set to acceptAllDevices: true, which would make it scan lists all opened nearby bluetooth devices. It returns a Promise.
try it
A Chrome browser test on your computer shows that it supports the API.
5. Channel Messaging API
Channel Messaging API MDN
The Channel Messaging API allows two different scripts to run in different browser contexts of the same document (such as two Iframes, or a document body and one IFrame, or two workers) to communicate directly. A port is used at each end to pass messages to each other through two-way channels.
Start by creating an instance of MessageChannel:
new MessageChannel()
Copy the code
This returns a MessagePort object (communication channel).
You can then set the port through messagePort. port1 or Messagechannel. port2.
The context in which MessageChannel is instantiated will use MessagePort.port1, and the other context will use MessagePort.port2. You can then use the postMessage API to deliver messages.
Each browser context listens for messages using message.onMessage and uses the event’s data property to get the Message content.
Let’s look at a simple example where we can use MessageChannel to send text between a document and an iframe.
Translator’s note: this demo, the original code has errors, translators have modified the code, the pro test can run normally
<body>
<header>
<h2>Web APIs<h2>
</header>
<div class="web-api-cnt">
<div class="web-api-card">
<div class="web-api-card-head"> Demo - MessageChannel </div>
<div class="web-api-card-body">
<div id="error" class="close"></div>
<div id="displayMsg">
</div>
<div>
<input id="input" type="text" placeholder="Send message to iframe" />
</div>
<div>
<button onclick="sendMsg()">Send Msg</button>
</div>
<div>
<iframe id="iframe" src="./iframe.content.html"></iframe>
</div>
</div>
</div>
</div>
</body>
<script>
try {
var channel = new MessageChannel()
var port1 = channel.port1
} catch (e) {
error.innerHTML = "MessageChannel API not supported in this device."
error.classList.remove("close")
}
iframe.addEventListener("load", onLoad)
function onLoad() {
port1.onmessage = onMessage
iframe.contentWindow.postMessage("load".The '*', [channel.port2])
}
function onMessage(e) {
const newHTML = "<div>" + e.data + "</div>"
displayMsg.innerHTML = displayMsg.innerHTML + newHTML
}
function sendMsg() {
port1.postMessage(input.value)
}
</script>
Copy the code
Notice the iframe tag, on which we loaded an iframe.content.html file. Buttons and text are where we type text and send messages to iframe.
const channel = new MessageChannel()
const port1 = channel.port1
iframe.addEventListener("load", onLoad)
function onLoad() {
port1.onmessage = onMessage
iframe.contentWindow.postMessage("load".The '*', [channel.port2])
}
function onMessage(e) {
const newHTML = "<div>" + e.data + "</div>"
displayMsg.innerHTML = displayMsg.innerHTML + newHTML
}
function sendMsg() {
port1.postMessage(input.value)
}
Copy the code
We initialize MessageChannel and port1. We added the Load listener to the iframe. Here, we register the OnMessage listener in port1 and use the postMessageAPI to send messages to iframe. Port2 is sent to iframe.
Let’s take a look at iframe’s iframe.content.html:
<body>
<div class="web-api-cnt">
<div class="web-api-card">
<div class="web-api-card-head">
Running inside an <i>iframe</i>
</div>
<div class="web-api-card-body">
<div id="iframeDisplayMsg">
</div>
<div>
<input placeholder="Type message.." id="iframeInput" />
</div>
<div>
<button onclick="sendMsgiframe()">Send Msg from <i>iframe</i></button>
</div>
</div>
</div>
</div>
</body>
<script>
var port2
window.addEventListener("message".function(e) {
port2 = e.ports[0]
port2.onmessage = onMessage
})
function onMessage(e) {
const newHTML = "<div>"+e.data+"</div>"
iframeDisplayMsg.innerHTML = iframeDisplayMsg.innerHTML + newHTML
}
function sendMsgiframe(){
port2.postMessage(iframeInput.value)
}
</script>
Copy the code
Here, we register a message event handler. We retrieve port2 and set the onMessage event handler on it. Now we can receive a message from the iframe and send it to its parent document.
try it
Note: This try does not work, you can copy the code above to try it locally
6. Vibration API
Vibration API MDN
Most modern mobile devices include vibration hardware, which allows software code to provide physical feedback to the user by making the device shake. The Vibration API provides Web applications with the ability to access this hardware (if it exists), and if the device does not support this feature, no action will be performed.
Navigator.vibrate (Pattern) controls the vibration, which is a single number or array of numbers describing the vibration pattern.
navigator.vibrate(200);
navigator.vibrate([200]);
Copy the code
Both examples can cause the device to vibrate for 200 ms and stop.
The navigator. Vibrate ([200.300.400])Copy the code
This causes the device to vibrate for 200 ms, pause for 300 ms, vibrate for 400 ms, and then stop.
Vibration can be stopped by passing 0, [], [0,0,0] (all zero group).
Let’s look at a simple demonstration:
<body>
<header>
<h2>Web APIs<h2>
</header>
<div class="web-api-cnt">
<div class="web-api-card">
<div class="web-api-card-head">
Demo - Vibration
</div>
<div class="web-api-card-body">
<div id="error" class="close"></div>
<div>
<input id="vibTime" type="number" placeholder="Vibration time" />
</div>
<div>
<button onclick="vibrate()">Vibrate</button>
</div>
</div>
</div>
</div>
</body>
<script>
if(navigator.vibrate) {
function vibrate() {
const time = vibTime.value
if(time ! ="")
navigator.vibrate(time)
}
} else {
error.innerHTML = "Vibrate API not supported in this device."
error.classList.remove("close")}</script>
Copy the code
We have input and a button. Enter the duration of the vibration in the input box and click the button. The device will vibrate at the input time
try it
The test worked fine on android phones
7. Broadcast Channel API
Broadcast Channel API MDN
The Broadcast Channel API allows messages or data from the same source to communicate in different browsing contexts. The browsing context can be a window, iframe, and so on.
The BroadcastChannel class is used to create or join channels.
const politicsChannel = new BroadcastChannel("politics")
Copy the code
Politics will be the name of the channel. Any context that initializes the BroadcastChannel constructor through Politics will join the channel, which will receive any messages sent on the channel and can send messages to the channel.
If it is the first constructor to use the BroadcastChannel, Politics creates the channel.
Be published to the channel, please use the BroadcastChannel. PostMessageAPI
To subscribe to the channel (listening to), please use the BroadcastChannel. The onmessage event.
To demonstrate the use of broadcast channels, I built a simple chat application:
<body>
<header>
<h2>Web APIs<h2>
</header>
<div class="web-api-cnt">
<div class="web-api-card">
<div class="web-api-card-head"> Demo - BroadcastChannel </div>
<div class="web-api-card-body">
<div class="page-info">Open this page in another <i>tab</i>.<i>window</i> or <i>iframe</i> to chat with
them.</div>
<div id="error" class="close"></div>
<div id="displayMsg" style="font-size:19px; text-align:left;">
</div>
<div class="chatArea">
<input id="input" type="text" placeholder="Type your message" />
<button onclick="sendMsg()">Send Msg to Channel</button>
</div>
</div>
</div>
</div>
</body>
<script>
const l = console.log;
try {
var politicsChannel = new BroadcastChannel("politics")
politicsChannel.onmessage = onMessage
var userId = Date.now()
} catch (e) {
error.innerHTML = "BroadcastChannel API not supported in this device."
error.classList.remove("close")
}
input.addEventListener("keydown".(e) = > {
if (e.keyCode === 13 && e.target.value.trim().length > 0) {
sendMsg()
}
})
function onMessage(e) {
const { msg, id } = e.data
const newHTML = "<div class='chat-msg'><span><i>" + id + "</i>: " + msg + "</span></div>"
displayMsg.innerHTML = displayMsg.innerHTML + newHTML
displayMsg.scrollTop = displayMsg.scrollHeight
}
function sendMsg() {
politicsChannel.postMessage({ msg: input.value, id: userId })
const newHTML = "<div class='chat-msg'><span><i>Me</i>: " + input.value + "</span></div>"
displayMsg.innerHTML = displayMsg.innerHTML + newHTML
input.value = ""
displayMsg.scrollTop = displayMsg.scrollHeight
}
</script>
Copy the code
PoliticsChannel is initialized and an onMessage event listener is set up on politicsChannel so that it can receive and display messages.
When the button is clicked, the sendMsg function is called. It sends messages to politicsChannel through the BroadcastChannel#postMessageAPI. Initialize the TAB page of the same script, where iframe or worker will receive messages sent, so the page can receive messages sent from other contexts.
Try it
8. Payment Request API
Payment Request API MDN
The Payment Request API provides a way to select a Payment route for goods and services.
The API provides a consistent way to provide payment details to different merchants without requiring the user to re-enter the details.
It provides merchants with billing addresses, shipping addresses, card details and more.
Note: This API provides user payment details, but does not introduce new payment methods.
Let’s look at a demo that demonstrates how to accept credit card payments using the payment request API:
<body>
<header>
<h2>Web APIs<h2>
</header>
<div class="web-api-cnt">
<div class="web-api-card">
<div class="web-api-card-head"> Demo - Credit Card Payment </div>
<div class="web-api-card-body">
<div id="error" class="close"></div>
<div>
<button onclick="buy()">Buy</button>
</div>
</div>
</div>
</div>
</body>
<script>
const networks = ["visa"."amex"]
const types = ["debit"."credit"]
const supportedInstruments = [
{
supportedMethods: "basic-card".data: {
supportedNetworks: networks,
supportedTypes: types
}
}
]
const details = {
total: {
label: "Total".amount: {
currency: "USD".value: "100"}},displayItems: [{label: "Item 1".amount: {
currency: "USD".value: "50"}}, {label: "Item 2".amount: {
currency: "USD".value: "50"]}}},try {
var paymentRequest = new PaymentRequest(supportedInstruments, details)
} catch (e) {
error.innerHTML = "PaymentRequest API not supported in this device."
error.classList.remove("close")}function buy() {
paymentRequest.show().then(response= > {
console.log(response)
})
}
</script>
Copy the code
Networks, types, and supportedTypes all describe payment modes. The details listed the items we purchased and the total cost.
Build the PaymentRequest instance, and paymentRequest.show() will display the payment interface in the browser. And process the user’s data in the Promise’s successful callback.
These are a number of configurations that use the Payment API to make payments, and at least from the examples above we’ve seen how the Payment Request API is used and how it works.
try it
I tested it, but I didn’t go through the whole process, because I definitely don’t pay
9. Resize Observer API
Resize Observer API MDN
The Resize Observer API provides a way to notify the Observer of any changes in the size of the elements registered with the Observer.
The ResizeObserver class provides an observer that will be invoked on each REsize event.
const resizeObserver = new ResizeObserver(entries= > {
for(const entry of entries) {
if(entry.contentBoxSize)
consoleo.log("element re-sized")
}
})
resizeObserver.observe(document.querySelector("div"))
Copy the code
Every time a div is resized, “Element re-sized” is printed on the console.
Let’s look at an example of how to use the Resize Observer API:
<body>
<header>
<h2>Web APIs<h2>
</header>
<div class="web-api-cnt">
<div class="web-api-card">
<div class="web-api-card-head">
Demo - ResizeObserver
</div>
<div class="web-api-card-body">
<div id="error" class="close"></div>
<div id="stat"></div>
<div id="resizeBoxCnt">
<div id="resizeBox"></div>
</div>
<div>
<span>Resize Width:<input onchange="resizeWidth(this.value)" type="range" min="0" max="100" value="0" /></span>
</div>
<div>
<span>Resize Height:<input onchange="resizeHeight(this.value)" type="range" min="0" max="100" value="0" /></span>
</div>
</div>
</div>
</div>
</body>
<script>
try {
var resizeObserver = new ResizeObserver(entries= > {
for(const entry of entries) {
stat.innerHTML = "Box re-sized. Height:" + entry.target.style.height + " - Width:" + entry.target.style.width
}
})
resizeObserver.observe(resizeBox)
} catch(e) {
error.innerHTML = "ResizeObserver API not supported in this device."
error.classList.remove("close")}function resizeWidth(e) {
resizeBox.style.width = `${e}px`
}
function resizeHeight(e) {
resizeBox.style.height = `${e}px`
}
</script>
Copy the code
We have the range slider here. If we slide them, they will change the width and height of idv#resizeBox. We registered the ResizeObserver observer on div#resizeBox to indicate that the message indicates that the box has been resized and the current value of its height and width.
Try sliding the range slider and you will see the change in the width and height of div#resizeBox. In addition, we will also see the information displayed in the div# stat box.
try it
10. Pointer Lock API
Pointer Lock API MDN
The Pointer Lock API is useful for applications that require a lot of mouse input to control motion, rotate objects, and change items. This is especially important for highly visual applications, such as those that use a first-person perspective, as well as 3D views and modeling.
Methods:
requestPointerLock
: This method removes the mouse from the browser and sends the mouse status event. This will continue until the call is madedocument.exitPointerLock
So far.document.exitPointerLock
: thisAPI
Release mouse pointer lock and restore mouse cursor.
Let’s look at an example:
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#box {
background-color: green;
width: 100%;
height: 400px;
position: relative;
}
#ball {
border-radius: 50%;
background-color: red;
width: 50px;
height: 50px;
position: absolute;
}
</style>
</head>
<body>
<header>
<h2>Web APIs<h2>
</header>
<div class="web-api-cnt">
<div class="web-api-card">
<div class="web-api-card-head"> Demo - PointerLock </div>
<div class="web-api-card-body">
<div id="error" class="close"></div>
<div id="box">
<div id="ball"></div>
</div>
</div>
</div>
</div>
</body>
<script>
const l = console.log
box.addEventListener("click".() = > {
if (box.requestPointerLock)
box.requestPointerLock()
else {
error.innerHTML = "PointerLock API not supported in this device."
error.classList.remove("close")}})document.addEventListener("pointerlockchange".(e) = > {
document.addEventListener("mousemove".(e) = > {
const { movementX, movementY } = e
ball.style.top = movementX + "px"
ball.style.left = movementY + "px"})})</script>
</html>
Copy the code
In div#box we have a div#box and div#ball.
We set up a click event on div#box that calls requestPointerLock() when clicked, which makes the cursor disappear.
PointerLock has a PointerlockChange event listener. This event is emitted when the pointer lock status changes. In its callback, we add it to the Mousemove event. When you move the mouse over the current browser TAB, its callback is triggered. In this callback, so we use it to get the current X and Y positions of the mouse. Using this information, we can set the top and left style properties for div#ball, so that when the mouse moves we see a dancing ball.
Two new parameters for mouse events, movementX and movementY, provide information about mouse position changes. When pointer locking is enabled, the normal MouseEvent properties clientX, clientY, screenX, and screenY remain unchanged as if the mouse is not moving.
try it
Note: This demo has some problems, so the try doesn’t work. You can copy the code above to create a local try.
conclusion
The Web is getting more complex. More and more native features are being used because there are far more Web users than native APP users. Users’ experiences with native apps are carried over to the Web so they don’t have to use native apps.
Well, if you see this, it’s true love. Do you want to add a star to my Github?
If there is any improper translation, please feel free to correct it in the comments section