【问题标题】:Refresh an image if new image is found如果找到新图像,则刷新图像
【发布时间】:2014-10-09 09:09:03
【问题描述】:

我在应用上每秒都在刷新来自网络摄像头的图像。我遇到的问题是,如果在几秒钟内没有从相机中检索到图像(这种情况经常发生),我最终会得到一个损坏的图像。我想拥有它,以便它仅在找到新图像时刷新。

目前为止

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);

如果没有检索到图像,是否可以停止刷新?

【问题讨论】:

  • onerror回调中处理

标签: javascript image function refresh


【解决方案1】:

遵循 sn-p 会有所帮助。

解决方案:

1) 创建动态图像对象

2) 绑定 onload 事件

3) 将动态创建的图像对象的 src 设置为所需的新图像链接

4) 动态图片加载成功后,替换原图标签或将原图标签的src设置为最新的图片链接

这样可以避免图像损坏的问题

代码:

var int_time;
(function(){
    var el = document.getElementById('myImage');
    function loadImage () {
        var img = new Image()
          , src = '<%= EVERCAM_API %>cameras/<%= @camera["id"] %>/snapshot.jpg?api_id=<%=  current_user.api_id %>&api_key=<%= current_user.api_key %>&rand=' + new Date().getTime();;
        img.onload = function() {
          if (!! el.parent)
            el.parent.replaceChild(img, el)
          else
            el.src = src;
        }
        img.src = src;
    }
    int_time = setInterval(loadImage, 1000);
}());

【讨论】:

    【解决方案2】:

    将它保存在一个变量中,然后检查变量的内容,但如果无法获取图像,我无法告诉你 api 返回什么。你需要自己解决这个问题,我在这里假设是错误的......

    var int_time = setInterval(function() {
        var myImageElement = document.getElementById('myImage');
        var newImage = '<%= EVERCAM_API %>cameras/<%= @camera["id"] %>/snapshot.jpg?api_id=<%=  current_user.api_id %>&api_key=<%= current_user.api_key %>&rand=' + new Date().getTime();
        if(newImage != false) { //Here you have to build an expression if the image is valid
            myImageElement.src = newImage;
        }
    }, 1000);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-16
      • 1970-01-01
      • 2023-02-05
      • 2011-09-24
      相关资源
      最近更新 更多