我正在使用 Cropper JS 库,在初始化裁剪框后设置数据时遇到一些问题。
https://github.com/fengyuanchen/cropper/blob/master/README.md http://fengyuanchen.github.io/cropper/
我在这里创建了一个 JSFiddle http://jsfiddle.net/vs2merje/1/
我的问题是我想在使用动态对象初始化 cropbox 后更改以下参数 {x,y,w,h}。
var imageURL = "http://i.imgur.com/zIQ92.jpg";
var imageBox = $('.img-container img');
//Initial crop box settings.
var options = {
aspectRatio: 1/2
};
//If condition is met, create a dynamic settings object to reset the box.
if(imageURL != null){
console.log("It's not empty, building dedault box!");
var DefaultCropBoxOptionObj = {
height: 25,
width: 25
};
console.log(DefaultCropBoxOptionObj);
imageBox.cropper(options);
imageBox.cropper('setData', DefaultCropBoxOptionObj);//add the dynamic settings.
imageBox.cropper('replace', imageURL);
}
正如您在 JSFiddle 中看到的那样,来自动态框的数据未应用于高度和宽度为 25px 的框。
谁能告诉我一些关于为什么会发生这种情况的见解?
谢谢。
最佳答案
解决方案
您需要使用 setCropBoxData
并在 built
事件中调用它。
replace
似乎有点问题(请参阅 issue 220 - Using replace() to update image to be cropped in a reactJS component )但我们可以通过在构建事件后触发一次来使其正常工作。在这里只触发“一次”很重要,否则它会创建一个循环,因为 replace
会触发 built
事件。
请注意,由于您使用的是 aspectRatio
,因此您不能同时设置宽度和高度。
我们还尽早声明 DefaultCropBoxOptionObj
以更好地可视化其范围。没有必要,只是为了安心。
$(document).ready(function(){
var imageURL = "http://i.imgur.com/zIQ92.jpg";
var imageBox = $('.img-container img');
var DefaultCropBoxOptionObj = {}; // declare early
var options = {
aspectRatio: 1/2,
built: function() {
imageBox.cropper('setCropBoxData', DefaultCropBoxOptionObj);
},
};
if(imageURL != null) {
// init
imageBox.cropper(options);
// set params
DefaultCropBoxOptionObj = {
width: 25,
left: 100,
};
// replace seems a bit buggy, fire once on built event
imageBox.one('built.cropper', function(){
imageBox.cropper('replace', imageURL);
});
}
});
演示
http://jsfiddle.net/j73xnbvf/5/
文档的相关部分
As there is an asynchronous process when load the image, you should call most of the methods after built, except "setAspectRatio", "replace" and "destroy".
来源:Image Cropper - README.md - Methods
setCropBoxData(data)
- data:
- Type: Object
- Properties:
- left: the new offset left of the crop box
- top: the new offset top of the crop box
- width: the new width of the crop box
- height: the new height of the crop box
Change the crop box position and size with new data.
关于javascript - 无法从动态数据对象设置裁剪器数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32056954/