我正在将裁剪工具集成到我的应用程序中。(杰克罗普)
我将以下JavaScript集成到页面中:
$(function() {
$("#imgInp").change(function(){
readURL(this);
});
});
function update_crop(coords) {
var rx = 100/coords.w;
var ry = 100/coords.h;
$('#preview').css({
width: Math.round(rx * 760) + 'px',
height: Math.round(ry * 1000) + 'px',
marginLeft: '-' + Math.round(rx * coords.x) + 'px',
marginTop: '-' + Math.round(ry * coords.y) + 'px'
});
}
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#cropbox').attr('src', e.target.result);
$('#preview').attr('src', e.target.result);
$('#cropbox').Jcrop({
onChange: update_crop,
onSelect: update_crop,
setSelect: [0, 0, 500, 500],
aspectRatio: 10 / 13.15
});
}
reader.readAsDataURL(input.files[0]);
}
}
在我的 HTML 中,我有以下内容:
<h1>Image to load</h1>
<form id="form1" runat="server">
<input type='file' id="imgInp" />
</form>
<img id="cropbox" src="#" alt="your image">
<h4>Preview:</h4>
<div style="width:100px; height:100px; overflow:hidden">
<img id="preview" src="#" alt="your image">
</div>
所以基本上我让用户上传图片的可能性,然后让他可视化要裁剪的区域。
问题是当我加载第一张图片时,它很好,但是当我第二次加载另一张图片时,它在img#cropbox
元素中没有变化。
所以基本上$('#cropbox').Jcrop
事件在浏览器更改$("#cropbox").attr('src',e.target.result)
之前执行
如何确保仅在执行$("#cropbox").attr('src',e.target.result)
并且图像完全加载时才执行$('#cropbox').Jcrop
?
图像元素也具有加载事件。在设置 src
属性之前,请将该函数包装在该图像上的加载事件回调中。
$('#cropbox').load(function(){
$('#cropbox').Jcrop({
onChange: update_crop,
onSelect: update_crop,
setSelect: [0, 0, 500, 500],
aspectRatio: 10 / 13.15
});
});
$('#cropbox').attr('src', e.target.result);
尝试设置间隔轮询以查看新图像源是否与预期的源匹配。
在继续执行 JCrop 之前,新的图像源(实际)应与预期的图像源(您设置的图像源)匹配。
下面是一个简化的示例:
function checkImageLoaded(newImg){
if (newImg == expectedImg){
$('#cropbox').Jcrop({
onChange: update_crop,
onSelect: update_crop,
setSelect: [0, 0, 500, 500],
aspectRatio: 10 / 13.15
});
//clear the interval
window.clearInterval(imageInterval);
}
}
function pollImageSource() {
//get the new Image source
//set the expect Image source
//then check if they match
var imageInterval = setInterval(function(){ checkImageLoaded(newImageSource); }, 300);
}
有很多图像插件可以检测图像是否已加载,但我认为没有必要。
此外,David Walsh有一个更强大的轮询机制。
https://davidwalsh.name/javascript-polling
摘录:
// Usage: ensure element is visible
poll(function() {
return document.getElementById('lightbox').offsetWidth > 0;
}, 2000, 150);
但这可能不起作用,因为您的图像已经加载。您必须大量修改该脚本才能比较图像源,如上所述。
我认为您应该使用图像的onload事件。 当浏览器完成渲染图像时,它会触发,每次图像更改时,它都会重新开始。
简单如点:
你可以用jQuery实现同样的目标: $("img").on("load",function() {....});
(前面有一个几乎相同的答案,对不起)