kennethcachia / background-check

Automatically switch to a darker or a lighter version of an element depending on the brightness of images behind it.
http://kennethcachia.com/background-check/
MIT License
3.27k stars 282 forks source link

Add Support for Object-Fit contain / cover #94

Open jakedowns opened 7 years ago

jakedowns commented 7 years ago

I was able to add support for object-fit elements, using the following 2 methods, from here http://stackoverflow.com/questions/37256745/object-fit-get-resulting-dimensions

  function getRenderedSize(contains, cWidth, cHeight, width, height, pos){
    var oRatio = width / height,
      cRatio = cWidth / cHeight;
    return function() {
      if (contains ? (oRatio > cRatio) : (oRatio < cRatio)) {
        this.width = cWidth;
        this.height = cWidth / oRatio;
      } else {
        this.width = cHeight * oRatio;
        this.height = cHeight;
      }
      this.left = (cWidth - this.width)*(pos/100);
      this.right = this.width + this.left;
      return this;
    }.call({});
  }

  function getImgSizeInfo(img) {
    var comp_style = window.getComputedStyle(img);
    var pos = comp_style.getPropertyValue('object-position').split(' ');
    var fit = comp_style.getPropertyValue('object-fit').trim();
    //console.log(fit);
    var contains = fit === 'contain' ? true : false; // contain v. cover
    return getRenderedSize(contains,
      img.width,
      img.height,
      img.naturalWidth,
      img.naturalHeight,
      parseInt(pos[0]));
  }

on my local copy, I've added it to the getArea method like so:

function getArea(obj) {
    /* ... */
    if (obj.nodeType) {
      /* ... */
      image = obj;

      // add support for object-fit
      var fit = $(obj).css('object-fit'); // default "fill" // TODO: replace jQuery dep here
      if(fit === 'contain' || fit === 'cover'){
        var data = getImgSizeInfo(obj);
        area.width = data.width;
        area.height = data.height;
      }
    } else {
      area = calculateAreaFromCSS(obj);
      /* ... */
    }
    /* ... */
    return area;
}

I might have time to do a pull request if you're interested.

jakedowns commented 7 years ago

This is not as straight-forward a request as I had initially thought... revisiting my solution...