信息详情:
我有一个图像编辑器,我在其中跟踪单击并拖动以使用 background-position
重新定位图像。我想自动居中图像并允许单击和拖动功能。我可以使用 center
或 50%
但单击和拖动使用像素,因此最好是:
- 找到图像的宽度和高度(我正在努力做到这一点)
- 找到包装 div 的宽度和高度(我可以做到这一点)
- 计算两者的中心(以像素为单位)并在
background-position
中设置这些值
我在 class
中使用 javascript File Loader API,如下所示:
this.reader.onload = file => {
// setting image on class via `this.reader.result`
};
如何在使用粗箭头携带上下文时获取文件的宽度和高度?可能吗?
最佳答案
这是加载图像并从中获取宽度/高度的方式。
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。
关于javascript - 使用带有像素的背景位置的中心图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59586296/