使用背景位置和像素的中心图像

时间:2020-01-03 22:55:13

标签: javascript css filereader background-position

信息详细信息: 我有一个图像编辑器,在其中跟踪单击和拖动以使用Update Transient UI State重新定位图像。我想使图像自动居中并允许单击和拖动功能。我可以使用background-positioncenter,但是单击和拖动使用的是像素,因此最好使用:

  1. 找到图像的宽度和高度(我正在努力做到这一点)
  2. 找到包装div的宽度和高度(我可以做到这一点)
  3. 计算两个像素的中心,并在50%中设置这些值

我正在background-position中使用javascript File Loader API,如下所示:

class

在使用粗箭头携带上下文时,如何获取文件的宽度和高度?有可能吗?

1 个答案:

答案 0 :(得分:0)

这是您加载图像并从中获取宽度/高度的方式。

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;


要获得以像素为单位的图像中心,只需将高度和宽度除以2。

相关问题