图片裁剪

527 阅读1分钟
  ImagecutFill(that, realWidth, realHeight) {
    let natureWidth; //原始宽度
    let natureHeight; //原始高度
    let vs; //图片宽高比
    natureWidth = that.naturalWidth;
    natureHeight = that.naturalHeight;


    let halfIntWidth = that.parentNode.clientWidth / 2;
    let halfIntHeight = that.parentNode.clientHeight / 2;
    vs = natureWidth / natureHeight;

    //缩略图比例240:160(等于1.5)
    if (vs >= 1.5) { //横图则固定高度
      if (realWidth > realHeight * vs) {
        $(that).css("width", realWidth + "px").css("height", "auto").css("marginTop", (halfIntHeight - (halfIntWidth *
          parseInt(natureHeight) / parseInt(natureWidth))) + "px").css("marginLeft", "0px");

      } else {
        $(that).css("width", "auto").css("height", realHeight + "px").css("marginLeft", (halfIntWidth - (
          halfIntHeight * parseInt(natureWidth) / parseInt(natureHeight))) + "px").css("marginTop", "0px");
      }
    } else { //
      if (realHeight > realWidth / vs) {
        $(that).css("width", "auto").css("height", realHeight + "px").css("marginLeft", (halfIntWidth - (
          halfIntHeight * parseInt(natureWidth) / parseInt(natureHeight))) + "px").css("marginTop", "0px");
      } else {
        $(that).css("width", realWidth + "px").css("height", "auto").css("marginTop", (halfIntHeight - (halfIntWidth *
          parseInt(natureHeight) / parseInt(natureWidth))) + "px").css("marginLeft", "0px");
      }
    }
  }