iT邦幫忙

2021 iThome 鐵人賽

DAY 12
0
Modern Web

後疫情時代的 WebRTC 微學習系列 第 12

Day12 [實作] 使用瀏覽器來拍照並加上濾鏡

上一篇嘗試了 WebRTC 的切換設備並顯示自己的影像,今天我們將通過上一次的程式碼來做拍照的功能並且加上一些濾鏡處理,我們將實作:

  1. 在視訊中取得畫面截圖

  2. 將圖片保存下來

  3. 在圖片上加上濾鏡

  4. 複製上一次的程式碼

    https://ithelp.ithome.com.tw/upload/images/20210926/20130062EO69WbODDI.png

    ❯ cd WebRTC/sample
    ❯ cp -r input-output take-a-photo
    
  5. 在 index.html video 標籤下增加

    ...
    <div><button id="shoot">拍照</button></div>
    ...
    
  6. main.js 中增加截圖的方法,傳入參數為 video 也就是顯示視訊的那個元件,方法內會產生一個canvas,並將 video 的畫面繪製在上面並回傳

    function capture(video) {
      const w = video.videoWidth
      const h = video.videoHeight
      const canvas = document.createElement('canvas')
      canvas.width = w
      canvas.height = h
      canvas.getContext('2d').drawImage(video, 0, 0, w, h)
      return canvas
    }
    
  7. main.js 中增加下載的方法,傳入url,方法內會產生一個 a 標籤,將要下載的內容寫入,並且點擊下載,最後把標籤刪除

    function download(url) {
      var a = document.createElement('a')
      a.download = 'Image.jpg'
      a.href = url
      document.body.appendChild(a)
      a.click()
      a.remove()
    }
    
  8. 把拍照的按鈕與下載功能綁定

    document.querySelector('button#shoot').onclick = () =>
      download(capture(videoElement).toDataURL('image/jpeg'))
    
  9. 加上濾鏡,在 index.html header 中加入 css ,以及一個選擇器。

    https://developer.mozilla.org/zh-CN/docs/Web/CSS/filter

    <head>
    ...
    <style>
      .none {
        -webkit-filter: none;
        filter: none;
      }
    
      .blur {
        -webkit-filter: blur(2px);
        filter: blur(2px);
      }
    
      .grayscale {
        -webkit-filter: grayscale(1);
        filter: grayscale(1);
      }
    
      .invert {
        -webkit-filter: invert(1);
        filter: invert(1);
      }
    
      .sepia {
        -webkit-filter: sepia(1);
        filter: sepia(1);
      }
    </style>
    </head>
    
    <body>
    ...
    <div>
      <label>濾鏡:</label>
      <select id="filter">
        <option value="none">None</option>
        <option value="blur">Blur</option>
        <option value="grayscale">Grayscale</option>
        <option value="invert">Invert</option>
        <option value="sepia">Sepia</option>
      </select>
    </div>
    ...
    </body>
    
  10. 在 main.js 中,加入濾鏡綁定

    const filtersSelect = document.querySelector('select#filter')
    filtersSelect.onchange = () => {
      videoElement.className = filtersSelect.value
    }
    
  11. 打開終端機 cd 到資料夾內並輸入 http-server ,使用瀏覽器開啟 http://localhost:8080 就可以查看效果了。

* http-server 安裝


上一篇
Day11 [實作] 如何在 WebRTC 中切換設備
下一篇
Day13 [實作] 把視訊及音訊內容錄製下來
系列文
後疫情時代的 WebRTC 微學習30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言