(编辑-我认为这是一个范围问题。我正在尝试从 javascript 访问 Jcrop 的实例,该实例是在初始页面加载后加载的,并且 Jcrop 已被调用。)
所以,我找到了一些关于如何执行此操作的重要信息,但我认为我的问题是我结合了 CoffeeScript 来创建 Jcrop 实例,后来我使用了 JavaScript 模板。
我很确定我无法访问我的 Jcrop 实例来使用 setImage 更新图像。
这是 CoffeeScript 文件:
jQuery ->
window.jcrop_api = new ProfilePicCropper()
class ProfilePicCropper
constructor: ->
$('#cropbox').Jcrop
aspectRatio: 1
setSelect: [0, 0, 600, 600]
onSelect: @update
onChange: @update
update: (coords) =>
$('#user_crop_x').val(coords.x)
$('#user_crop_y').val(coords.y)
$('#user_crop_w').val(coords.w)
$('#user_crop_h').val(coords.h)
@updatePreview(coords)
updatePreview: (coords) =>
$('#preview').css
width: Math.round(100/coords.w * $('#cropbox').width()) + 'px'
height: Math.round(100/coords.h * $('#cropbox').height()) + 'px'
marginLeft: '-' + Math.round(100/coords.w * coords.x) + 'px'
marginTop: '-' + Math.round(100/coords.h * coords.y) + 'px'
并且,稍后在加载到同一页面的 JavaScript 模板中,我想更新该图像,但无法让它工作:
<% if @user.new_record? %>
alert("Failed to upload picture: <%= j @user.errors.full_messages.join(', ').html_safe %>");
<% else %>
jcrop_api.setImage("<%= @user.profilepic.url(:large_pic) %>", function(j){
jcrop_api.setOptions({ onChange: updatePreview,
onSelect: updatePreview });
bounds = jcrop_api.getBounds();
boundx = bounds[0];
boundy = bounds[1];
});
<% end %>
因此,我按照 StackOverflow 的建议在 CoffeeScript 中尝试了各种全局声明,以及 setImage 的一些变体,但我的图像仍然没有更新。有什么帮助吗?
最佳答案
问题已解决...
问题源于 CoffeeScript 。我没有获得 Jcrop 插件的适当句柄。基本上是两个问题。
获取 Jcrop 句柄的正确的 CoffeeScript 语法:
class ProfilePicCropper
constructor: ->
$('#cropbox').Jcrop
aspectRatio: 1
setSelect: [0, 0, 600, 600]
onSelect: @update
onChange: @update
() -> window.jcrop_api = this
最后一行基本上解决了我所有的问题。该调用需要函数调用,而这正是我没有正确执行的操作。
当然,coffeescript 封装变量也存在范围问题。通过将句柄附加到窗口可以解决该问题。
关于javascript - 更新 Rails 站点中的 Jcrop 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35022065/