前端實現一個最近抖音很火的圖片選擇題特效

語言: CN / TW / HK

程式碼片段

掘金由於安全原因沒有在 iframe標籤上設定allow="microphone ;camera "導致攝像頭開啟失敗!請點選右上角“檢視詳情”檢視!或點選下方連結檢視

http://wangpeng1478.github.io/web/ImageSelect/

前言

最近抖音特效中有個圖片選擇題特別火,今天就來講一下前端如何實現,下面我主要講一下如何判斷左右擺頭

人臉識別的技術可以看前一段時間寫的 前端實現活體人臉檢測這篇文章。

如何判斷

找到人臉上的兩個兩個點

第一個點 額頭中心位置 第二個點 下巴中心位置

js const place1 = (face.keypoints || []).find((e,i)=>i===10); //額頭位置 const place2 = (face.keypoints || []).find((e,i)=>i===152); //下巴位置 /* x1,y1 | | | x2,y2 -------|------- x4,y4 x3,y3 */ const [x1,y1,x2,y2,x3,y3,x4,y4] = [ place1.x,place1.y, 0,place2.y, place2.x,place2.y, this.canvas.width, place2.y ]; 通過canvas.width 額頭中心位置下巴中心位置計算出 x1,y1,x2,y2,x3,y3,x4,y4

tutieshi_528x232_6s.gif getAngle({ x: x1, y: y1 }, { x: x2, y: y2 }){ const dot = x1 * x2 + y1 * y2 const det = x1 * y2 - y1 * x2 const angle = Math.atan2(det, dot) / Math.PI * 180 return Math.round(angle + 360) % 360 } const angle = this.getAngle({ x: x1 - x3, y: y1 - y3, }, { x: x2 - x3, y: y2 - y3, }); console.log('角度',angle) image.png

通過獲取角度,通過角度的大小來判斷左右擺頭。