javascriptcssfilereaderbackground-position

center Image using background position with pixels


information details: I have an image editor where I'm tracking a click and drag to re-position an image using background-position. I want to auto center the image and allow the click and drag functionality. I could use center or 50% but the click and drag is using pixels so it's preferable that I:

  1. find the image width and height (I'm struggling to do this)
  2. find the wrapping div width and height (I can do this just fine)
  3. calculate the center of both in pixels and set those values in background-position

I'm using the javascript File Loader API in a class like so:

this.reader.onload = file => {
      // setting image on class via `this.reader.result`
    };

How do I get the width and height of the file while carrying context with the fat-arrow? Is it possible?


Solution

  • This is how you load an image and get the width/height from it.

    var image = new Image();
    
    image.onload = function() { 
      // the onload function will be called when the image has been loaded
      var height = img.height;
      var width = img.width;
    
      // more code here
    }
    
    image.src = url;
    


    To get the center of the image in pixels, simply divide both the height and the width by 2.