Javascript 更新映像如果找不到,请停止更新
我正在从相机中获取图像,并每秒更新一次以下内容:Javascript 更新映像如果找不到,请停止更新,javascript,Javascript,我正在从相机中获取图像,并每秒更新一次以下内容: <img id="myImage" style="width: 100%" src="<%= EVERCAM_API %>cameras/<%= @camera['id'] %>/snapshot.jpg?api_id=<%= current_user.api_id %>&api_key=<%= current_user.api_key %>" /> <script ty
<img id="myImage" style="width: 100%" src="<%= EVERCAM_API %>cameras/<%= @camera['id'] %>/snapshot.jpg?api_id=<%= current_user.api_id %>&api_key=<%= current_user.api_key %>" />
<script type="text/javascript">
var int_time = setInterval(function() {
var myImageElement = document.getElementById('myImage');
myImageElement.src = '<%= EVERCAM_API %>cameras/<%= @camera["id"] %>/snapshot.jpg?api_id=<%= current_user.api_id %>&api_key=<%= current_user.api_key %>&rand=' + new Date().getTime();
}, 1000);
</script>
问题是,如果在一段时间内我无法从相机中获得图像,我会得到一个损坏的图像。我想发生的是,如果我没有得到一个更新的图像-该图像不会尝试刷新。
我已经尝试了以下几点,但我就是无法让它发挥作用:
var jQuery,
url = '<%= EVERCAM_API %>cameras/<%= @camera["id"] %>/snapshot.jpg?api_id=<%= current_user.api_id %>&api_key=<%= current_user.api_key %>&rand=' + new Date().getTime();',
refresh = 1000,
priv = <%= params[:private] %>,
iframeStyle = "width: 100%; height:100%;",
imgStyle = "width: 100%;";
function updateImage() {
if (refresh > 0) {
window.ec_watcher = setTimeout(updateImage, refresh);
}
jQuery("<img style='" + imgStyle + "'/>").attr('src', url + '?' + new Date().getTime())
.load(function() {
if (!this.complete || this.naturalWidth === undefined || this.naturalWidth === 0) {
console.log('broken image!');
} else {
container.empty().append(jQuery(this))
console.log('updated');
}
});
}
我只是很难让第二个想法真正起作用 什么方法不起作用?您是否意识到第二行的末尾有一个额外的“a”?请不要更新显示在用户图像中的“a”。创建一个不属于dom的新img对象,对其执行.src操作,确认它已加载ok,然后将该图像插入dom。没有img被加载,您只需继续显示旧的/原始的img。