學會使用這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

最後,如果您對此有任何疑問,請隨時發表評論。感謝閱讀,謝謝!!!

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