简体   繁体   English

使用带像素的背景位置居中图像

[英]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 .信息详细信息:我有一个图像编辑器,我在其中跟踪单击并拖动以使用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:我可以使用center50%但点击和拖动使用像素所以我最好:

  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)找到包装 div 的宽度和高度(我可以很好地做到这一点)
  3. calculate the center of both in pixels and set those values in background-position以像素为单位计算两者的中心并将这些值设置在background-position

I'm using the javascript File Loader API in a class like so:我在一个class使用 javascript File Loader API,如下所示:

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?是否可以?

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.要以像素为单位获得图像的中心,只需将高度和宽度除以 2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM