javascript 如何仅在完全加载时显示图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14373683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:28:28  来源:igfitidea点击:

how to show image only when it is completely loaded?

javascripthtml

提问by Sarfraz Ahmed

I have an img tag on my web page. I give it the url for an IP camera from where it get images and display them. I want to show image when it is completely loaded. so that I can avoid flickering. I do the following.

我的网页上有一个 img 标签。我给它一个 IP 摄像机的 URL,它从那里获取图像并显示它们。我想在完全加载时显示图像。这样我就可以避免闪烁。我执行以下操作。

<img id="stream"
  width="1280" height="720" 
  alt="Press reload if no video displays" 
  border="0" style="cursor:crosshair; border:medium; border:thick" />

<button type="button" id="btnStartLive" onclick="onStartLiveBtnClick()">Start Live</button>

javascript code

javascript代码

function LoadImage()
{
  x = document.getElementById("stream");    
  x.src = "http://IP:PORT/jpg/image.jpg" + "?" + escape(new Date());
}

function onStartLiveBtnClick()
{       
  intervalID = setInterval(LoadImage, 0);
}

in this code. when image is large. it takes some time to load. in the mean time it start showing the part of image loaded. I want to display full image and skip the loading part Thanks

在这段代码中。当图像很大时。加载需要一些时间。同时它开始显示加载的图像部分。我想显示完整图像并跳过加载部分谢谢

回答by Andreas

Preload the image and replace the source of the <img />after the image has finished loading.

预加载图像并<img />在图像加载完成后替换源。

function LoadImage() {
    var img = new Image(),
        x = document.getElementById("stream");

    img.onload = function() {
        x.src = img.src;
    };

    img.src = "http://IP:PORT/jpg/image.jpg" + "?_=" + (+new Date());
}

回答by laurent

You can use the completeproperty to check if the image has finished loading. However, I think there are other issues with your code, mainly you are repeatedly loading the same image. Instead, you should load it only once and then check the completeproperty in an interval.

您可以使用该complete属性来检查图像是否已完成加载。但是,我认为您的代码还有其他问题,主要是您重复加载相同的图像。相反,您应该只加载一次,然后complete每隔一段时间检查一次属性。

Something like this should work:

这样的事情应该工作:

function LoadImage()
{
  x = document.getElementById("stream");    
  x.src = "http://IP:PORT/jpg/image.jpg" + "?" + escape(new Date());
  x.style.visibility = 'hidden';
}

function CheckIsLoaded() {
  x = document.getElementById("stream");    
  if (x.complete) x.style.visibility = 'visible';
}

function onStartLiveBtnClick()
{       
  LoadImage();
  intervalID = setInterval(CheckIsLoaded, 0);
}