学会使用这10个有用的Web API,让你的开发效率瞬间提升10倍

英文| https://blog.bitsrc.io/10-useful-web-apis-for-2020-8e43905cbdc5

翻译| web前端开发(ID:web_qdkf)

(如Web Worker,Fetch等),但是我个人更喜欢使用其他一些不太流行的API,我建议你也尝试一下。

在这篇文章中所描述的所有Web API有实时示例,并且你都可以在以下地址中找到他们:

Web API地址:https:///web-api-examples.github.io/

你还可以在这里:https://github.com/web-api-examples/web-api-examples.github.io

找到描述Web API的所有源代码。

1,网络音频API

学习地址:https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Audio_API

网络音频API允许您在Web上操作音频流。它可用于向网络上的音频源添加效果和滤镜。

音频源主要通过<audio>元素来添加,其包括视频/音频源文件或音频网络流。

下面,让我们看一个简单的例子:

<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="./audio.mp3" id="audio"></audio>                </div>
                <div>                    <button οnclick="audioFromAudioFile.init()">Init</button>                    <button οnclick="audioFromAudioFile.play()">Play</button>                    <button οnclick="audioFromAudioFile.pause()">Pause</button>                    <button οnclick="audioFromAudioFile.stop()">Stop</button>                </div>                <div>
                    <span>Vol: <input οnchange="audioFromAudioFile.changeVolume()" type="range" id="vol" min="1" max="2" step="0.01" value="1" /></span>                    <span>Pan: <input οnchange="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)            }            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 = this.value            l("Vol Range:",this.value)        }
        function changePan() {            pannerNode.gain.value = this.value            l("Pan Range:",this.value)        }
        return {            init,            play,            pause,            stop,            changePan,            changeVolume        }    })()</script>

声音效果(例如声像)在添加到音频输出(扬声器)之前已添加到音频源。本示例将将音频从<audio>元素传递到AudioContext。

这将创建一个AudioContext实例合并其设置为audioContext。 

接下来,重新创建媒体源createMediaElementSource(音频),将音频元素作为音频源传递。

在这里,我们调整音频的音量。然后,使用StereoPannerNode设置平移效果。最后,将连接到媒体源。

按钮(播放,暂停,停止)播放,暂停和停止音频。

我们有一个“音量和声像范围”滑块,更改它们会影响音量和音频的声像效果。

你可以在这里试试:h  ttps://web-api-examples.github.io/audio.html。

实例演示地址:https://codepen.io/Rumyra/pen/qyMzqN

截图如下:

2,全屏API

学习地址:https://developer.mozilla.org/zh-CN/docs/Web/API/Fullscreen_API

全屏API在Web应用程序中启用全屏模式。您可以选择在全屏模式下查看元素。在Android手机中,删除浏览器窗口和Android顶部状态栏(在其中显示网络状态,电池状态等)。

方法:

requestFullscreen在系统上以全屏模式显示扩展的元素,从而关闭其他应用程序以及浏览器和系统UI元素。

exitFullscreen将全屏模式退出到正常模式。

让我们看一个简单的示例,其中我们可以使用全屏模式观看视频:

<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="./video.mp4"></video>            <button οnclick="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")    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>

看到video元素在div#video-stage元素中,并带有“切换全屏”按钮。

当我们逐步切换全屏按钮时,我们要使元素div#video-stage变成全屏。

参见功能切换:

function toggle() {    const videoStageEl = document.querySelector(".video-stage")    if(!document.fullscreenElement)        videoStageEl.requestFullscreen()    else        document.exitFullscreen()}

它查询div#video-stage元素加上其HTMLDivElement实例保留在上videoStageEl。

我们使用document.fullsreenElement属性知道该文件是否未处于全屏,所以我们可以调用requestFullscreen()上videoStageEl。这将div#video-stage接管整个设备视图。

如果在全屏模式下切换全屏按钮,exitFullcreen将在文档上调用,因此UI视图将返回到普通视图。

你可以在这里试试:https://web-api-examples.github.io/fullscreen.html

3,Web Speech API

学习地址:https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Speech_API/Using_the_Web_Speech_API

此API为我们提供了将语音合成和语音识别添加到我们的Web应用程序的功能。

使用此API,我们将能够向网络应用发出语音命令,就像在Android上通过其Google Speech或在Windows中使用Cortana一样。

让我们看一个简单的例子。我们将看到如何使用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 οnclick="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 οnclick="tapToSpeak()">Tap and Speak into Mic</button>                </div>            </div>        </div>
    </div></body>
<script>
    try {        var speech = new SpeechSynthesisUtterance()        var SpeechRecognition = SpeechRecognition;        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        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>

第一个演示文稿-文本到语音演示了如何通过一个简单的输入分段使用此API来接收输入文本和一个用于执行语音操作的按钮。

请参见语音功能:

function speak() {        const speech = new SpeechSynthesisUtterance()        speech.text = textToSpeech.value        speech.volume = 1        speech.rate = 1        speech.pitch = 1        window.speechSynthesis.speak(speech)    }

它实例化SpeechSynthesisUtterance()对象,设置文本,放置与我们在输入键入键入的文本说话。然后,调用语音对象的SpeechSynthesis#speak函数,使输入文本的文本在我们的扬声器中响亮。

我们两次并讲话进入麦克风按钮,对着麦克风语音,我们说的语言会在文本区域中被翻译成文字。

点击并讲话进入麦克风顶部后的按钮调用该tapToSpeak函数:

function tapToSpeak() {        var SpeechRecognition = SpeechRecognition;        const recognition = new SpeechRecognition()        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()    }

很简单,语音识别实例化,然后注册事件处理程序和替换。onstart在语音识别开始时出错,在发生错误时调用。onresult每当语音识别捕获到一条线时,就会调用。

因此当我们对着麦克风说话时,这些文字会出现在文本区域内容中。

你可以在这里试试:https://web-api-examples.github.io/speech.html

4,蓝牙API

学习地址:https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Bluetooth_API

实验技术

通过此API,我们可以访问手机上的低功耗蓝牙设备,并使用串行网页中的数据共享到另一台设备。

想象一下能够创建一个网络聊天应用程序,该应用程序可以通过蓝牙发送和接收来自其他手机的消息。

可能是无止境。

基本的API是navigator.bluetooth.requestDevice。调用称为浏览器提示用户一个设备选择器,使他们可以选择一个设备或取消请求。

navigator.bluetooth.requestDevice需要一个强制对象。该对象定义了用于返回与过滤器匹配的蓝牙设备的过滤器。

让我们看一个简单的演示。本演示将使用navigator.bluetooth.requestDeviceAPI从BLE设备检索基本设备信息。

<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 οnclick="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>

设备的信息显示在此处。该该按钮可获取BLE设备调用该bluetoothAction功能。

function bluetoothAction(){        navigator.bluetooth.requestDevice({            acceptAllDevices: true        }).then(device => {                        dname.innerHTML = device.name            did.innerHTML = device.id            dconnected.innerHTML = device.connected        }).catch(err => {            console.error("Oh my!! Something went wrong.")        })    }

该bluetoothAction函数navigator.bluetooth.requestDevice使用选项调用API acceptAllDevices:true,这将转换扫描并列出附近所有具有蓝牙功能的设备。获取一个参数,该设备参数将保存列出的蓝牙设备的信息。这是我们使用其属性在设备上显示信息的地方。

在这里尝试:https://web-api-examples.github.io/bluetooth.html

5,频道消息传递API

学习地址:https://developer.mozilla.org/zh-CN/docs/Web/API/Channel_Messaging_API

该API允许在不同的浏览器区域中的两个脚本在双向通道中相互通信并传递消息。

不同的浏览器上下文可以是在不同选项卡中运行的两个脚本,脚本中的两个iframe,文档和脚本中的iframe等。

首先创建一个MessageChannel实例:

new MessageChannel()

这将返回一个MessagePort对象。

然后,每个浏览器某个都可以使用MessagePort.port1或MessageChannel.port2设置端口。

实例化MessageChannel的一部分将使用MessagePort.port1,另一个将使用MessagePort.port2。

然后,可以使用postMessage API传递消息。

每个浏览器都会都将使用Message.onmessage收听消息。

让我们看一个简单的示例,在这里我们可以使用MessageChannel在文档和iframe之间发送文本。

<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 οnclick="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", channel.port2)            }
    function onMessage(e) {                const newHTML = "<div>"+e.data+"</div>"        displayMsg.innerHTML = displayMsg.innerHTML + newHTML    }
    function sendMsg() {        iframe.contentWindow.postMessage(input.value, channel.port2)    }</script>

请注意iframe广告代码。我们在上面加载了一个iframe.content.html文件。按钮和文本是我们输入文字并向iframe发送消息的地方。

<script>    const channel = new MessageChannel()    const port1 = channel.port1    iframe.addEventListener("load", onLoad)    function onLoad() {        port1.onmessage = onMessage        iframe.contentWindow.postMessage("load", channel.port2)            }    function onMessage(e) {                const newHTML = "<div>"+e.data+"</div>"        displayMsg.innerHTML = displayMsg.innerHTML + newHTML    }    function sendMsg() {        iframe.contentWindow.postMessage(input.value, channel.port2)    }</script>

在这里,我们在onmessage上注册了侦听器端口1,然后使用postMessage API将消息发送到iframe。看到通道2被向下发送到iframe。

让我们看一下iframe的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 οnclick="sendMsgiframe()">Send Msg from <i>iframe</i></button>                </div>
            </div>        </div>
    </div></body>
<script>    var port2    const l = console.log    window.addEventListener("message", function(e) {        l(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>

在这里,我们注册了一个消息事件处理程序。我们检索,port2并在消息上设置设置事件处理程序。现在,我们可以从iframe接收消息将其发送到其父文档。

在这里尝试https  :  //web-api-examples.github.io/channelmessaging.html

6,振动API

学习地址:https://developer.mozilla.org/zh-CN/docs/Web/API/Vibration_API

振动API能使我们的设备振动,以作为对新数据或信息的通知或物理反馈的方式,我们应进行响应。

执行此操作的方法是navigator.vibrate(模式)。

模式是描述振动模式的个别数字或数字副本。

navigator.vibrate(200)navigator.vibrate([200])

这将使设备振动200毫秒并停止。

navigator.vibrate([200, 300, 400])

这将使设备振动200毫秒,暂停300毫秒,振动400毫秒,然后停止。

可以通过传递0,[](全为零的副本[0,0,0])来消除振动。

让我们看一个简单的演示:

<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 οnclick="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>

我们有输入和一个按钮。在输入附件输入振动的持续时间,然后按按钮。

你的设备将在输入的加速度振动。

你可以在这里尝试一下:https  :  //web-api-examples.github.io/vibration.html

7,广播频道API

学习地址:https://developer.mozilla.org/zh-CN/docs/Web/API/Broadcast_Channel_API

此API支持来自同一来源的不同浏览部分的消息或数据进行通信。

浏览某些是窗口,标签,iframe,工作程序等

BroadcastChannel类用于创建或加入频道。

const politicsChannel = new BroadcastChannel("politics")

初始化广播频道构造函数的任何政治都柏林将加入政治频道,从而接收在该频道上发送的任何消息,并且可以将消息发送到该频道。

如果是第一个到BroadcastChannel的构造函数,politics插入创建该频道。

要发布到频道,请使用BroadcastChannel.postMessageAPI

要订阅频道(监听消息),请使用BroadcastChannel.onmessage事件。

为了演示广播频道的用法,我内置了一个简单的聊天应用程序:

<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 οnclick="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>

我从设置UI视图开始。这是一个简单的文本和按钮。输入你的信息,然后按按钮发送信息。

在脚本部分,我初始化了politicsChannel,并在上设置了一个onmessage事件侦听器politicsChannel,因此可以接收并显示消息。

该sendMsg功能由按钮调用。它的政治频道通过广播频道#postMessageAPI将消息发送到。。

你可以在这里尝试:

https://web-api-examples.github.io/broadcastchannel.html

8,付款请求API

推荐阅读:https://developer.mozilla.org/zh-CN/docs/Web/API/Payment_Request_API

该API提供了一种选择商品和服务到支付网关的支付方式的方法。

支持一种一致的方式来向不同的商家提供付款细节,而无需用户再次输入细节。

它向商家提供帐单地址,送货地址,卡详细信息等信息。

注意:此API不会为表格带来新的付款方式。它提供了用户付款明细。

让我们看一个演示:如何使用付款请求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 οnclick="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 => {            log(instrument)        })    }</script>

网络,类型和supportedTypes都描述了付款方式。

详细信息列出我们的购买和总费用。

现在,PaymentRequest使用支持的类型传递给PaymentRequest结构函数的和详细信息实例化。

paymentRequest.show()将显示浏览器付款用户界面。然后,我们处理解决Promise时用户提供的数据。

它们是使用付款API进行付款的许多配置,至少通过以上示例,我们已经了解了付款请求API的使用方式和工作方式。

在这里尝试现场演示:

https://web-api-examples.github.io/paymentrequest.html

9,调整观察者API的大小

学习地址:https://developer.mozilla.org/zh-CN/docs/Web/API/Resize_Observer_API

该API提供了一种方式,如果以任何方式调整了注册观察者的元素的大小,则可以通知观察者。

ResizeObserver类提供了一个观察者,该观察者将在每个resize事件上调用。

const resizeObserver = new ResizeObserver(entries => {    for(const entry of entries) {        if(entry.contentBoxSize)            consoleo.log("element re-sized")    }})resizeObserver.observe(document.querySelector("div"))

调整调整div大小时,控制台上都会打印“ element re-sized”。

让我们看一下如何使用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 οnchange="resizeWidth(this.value)" type="range" min="0" max="100" value="0" /></span>                </div>
                <div>                    <span>Resize Height:<input οnchange="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>

我们在这里有范围滑块。如果我们滑动它们,它们将改变高度和宽度idv#resizeBox。和宽度的当前值的消息。

尝试滑动范围滑块,您将看到div#resizeBox宽度和高度的变化,从而,我们看到信息显示在div#stat位置。

你可以在这里尝试一下:

https://web-api-examples.github.io/resizeobserver.html

10,指针锁定API

学习地址:https://developer.mozilla.org/zh-CN/docs/Web/API/Pointer_Lock_API

该API可以无限制地访问鼠标输入,座标,动作和移动。

非常适合玩游戏,为3D模型建模等。

这些API是:

requestPointerLock:此方法重置浏览器中删除鼠标并发送鼠标状态事件。这将持续到exitPinterLock调用为止。

exitPointerLock:此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 - 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>

我们有一个div#box和div#ball里面的div#box。

我们在上设置了clickEventdiv#box,因此初始化它会调用requestPointerLock(),这导致光标消失。

PointerLock有一个pointerlockchange事件侦听器。当指针锁定状态更改时,将发出此事件。在其替代中,我们将其附加到mousemove事件。在此之后中,当前鼠标位置被发送到e参数,因此我们使用它来获取鼠标的当前X和Y位置。使用此信息,我们可以设置顶部和标题样式属性div#ball,因此,当鼠标移动时,我们会看到一个跳舞的球。

你可以在这里尝试:

https://web-api-examples.github.io/pointerlock.html

最后,如果您对此有任何疑问,请随时发表评论。感谢阅读,谢谢!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章