前端實現(xiàn)圖片和視頻的居中裁剪

1. 圖片裁剪效果 -- 用css可實現(xiàn)

方法:就是把圖片作為標簽的背景色, css控制圖片的位置

  {
    height: 100%;
    background-image: url(/*image地址*/);
    background-size: cover;
    background-position: center;
}  

2. 視頻裁剪效果 -- 用js可實現(xiàn)

方法:需要獲取視頻的高度和寬度,然后根據(jù)所在區(qū)域的比例,設置video的height和width屬性值(100%和auto中切換,本例以9/16為例,所在區(qū)域寬高分別是:375 * 667

let ele = document.getElementsByTagName('video')
if (ele[0]) {
  let {width = 0, height = 0, left = 0, top = 0} = this.video || {} 
  #this.data 指向視頻的信息

  if (width && height && full) {
    if (width / height > 9/16) {
      left = (width * 667 / height - width) / 2
      ele[0].setAttribute('width', 'auto')
      ele[0].style.position = 'absolute'
      ele[0].style.left = `-${left}px`
    } else {
      top = (height * 375 / width - height) /2
      ele[0].setAttribute('height', 'auto')
      ele[0].style.position = 'absolute'
      ele[0].style.top = `-${top}px`
    }
  }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容