亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

模擬背景大?。涸诋嫴忌细采w

模擬背景大?。涸诋嫴忌细采w

我正在畫像這樣的畫布:ctx.drawImage(data[i].image, data[i].pos.x, data[i].pos.y, data[i].pos.w, data[i].pos.h);問題是圖片越來越拉伸,我不希望這樣。我如何模擬css屬性background-size: cover在卡瓦斯畫圖像。http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size&preval=cover看看100% 100%(我現在擁有的)和cover(我的目標)之間的區別。
查看完整描述

2 回答

?
慕萊塢森

TA貢獻1810條經驗 獲得超4個贊

如果您正在尋找一種適用于大多數情況的簡單解決方案,并且還包括類似CSS contain的功能,請嘗試以下方法:


function fit(contains) {

  return (parentWidth, parentHeight, childWidth, childHeight, scale = 1, offsetX = 0.5, offsetY = 0.5) => {

    const childRatio = childWidth / childHeight

    const parentRatio = parentWidth / parentHeight

    let width = parentWidth * scale

    let height = parentHeight * scale


    if (contains ? (childRatio > parentRatio) : (childRatio < parentRatio)) {

      height = width / childRatio

    } else {

      width = height * childRatio

    }


    return {

      width,

      height,

      offsetX: (parentWidth - width) * offsetX,

      offsetY: (parentHeight - height) * offsetY

    }

  }

}


export const contain = fit(true)

export const cover = fit(false)

內部比例的略微修改版本,包括比例和偏移


用法:


import {cover, contain} from './intrinsic-scale'


const {

  offsetX, 

  offsetY, 

  width, 

  height

} = cover(parentWidth, parentHeight, imageWidth, imageHeight)


// or...


const {

  offsetX, 

  offsetY, 

  width, 

  height

} = contain(parentWidth, parentHeight, imageWidth, imageHeight)


ctx.drawImage(image, offsetX, offsetY, width, height)


查看完整回答
反對 回復 2019-09-02
  • 2 回答
  • 0 關注
  • 610 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號