JavaScript:如何强制Image()不使用浏览器缓存? [英] JavaScript: how to force Image() not to use the browser cache?

查看:227
本文介绍了JavaScript:如何强制Image()不使用浏览器缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在浏览器中手动加载nextimg URL,则每次重新加载时都会显示新图片。但是这段代码在 draw()的每次迭代中显示相同的图像。

If I load the nextimg URL manually in the browser, it gives a new picture every time I reload. But this bit of code shows the same image every iteration of draw().

如何强制myimg不要缓存?

How can I force myimg not to be cached?

<html>
  <head>
    <script type="text/javascript">
      function draw(){
        var canvas = document.getElementById('canv');
        var ctx = canvas.getContext('2d');
        var rx;
        var ry;
        var i;

        myimg = new Image();
        myimg.src = 'http://ohm:8080/cgi-bin/nextimg'

        rx=Math.floor(Math.random()*100)*10
        ry=Math.floor(Math.random()*100)*10
        ctx.drawImage(myimg,rx,ry);
        window.setTimeout('draw()',0);
      }
    </script>
  </head>
  <body onload="draw();">
    <canvas id="canv" width="1024" height="1024"></canvas>
  </body>
</html>


推荐答案

这听起来像浏览器中的错误 - 您可以在 http://bugs.webkit.org 上提交,如果它在Safari中或 https://bugzilla.mozilla.org/ for Firefox。为什么我说潜在的浏览器错误?因为浏览器意识到它不应该在重新加载时缓存,但是当你以编程方式请求它时它会给你一个缓存的图像副本。

That actually sounds like a bug in the browser -- you could file at http://bugs.webkit.org if it's in Safari or https://bugzilla.mozilla.org/ for Firefox. Why do i say potential browser bug? Because the browser realises it should not be caching on reload, yet it does give you a cached copy of the image when you request it programmatically.

那说你确定你实际上是在画任何东西? Canvas.drawImage API不会等待加载图像,并且当您尝试使用图像时,如果图像没有完全加载,则指定不绘制。

That said are you sure you're actually drawing anything? the Canvas.drawImage API will not wait for an image to load, and is spec'd to not draw if the image has not completely loaded when you try to use it.

更好的做法是:

    var myimg = new Image();
    myimg.onload = function() {
        var rx=Math.floor(Math.random()*100)*10
        var ry=Math.floor(Math.random()*100)*10
        ctx.drawImage(myimg,rx,ry);
        window.setTimeout(draw,0);
    }
    myimg.src = 'http://ohm:8080/cgi-bin/nextimg'

(您也可以将 draw 作为参数传递给setTimeout而不是使用字符串,这将保存重组并反复编译相同的字符串再次。)

(You can also just pass draw as an argument to setTimeout rather than using a string, which will save reparsing and compiling the same string over and over again.)

这篇关于JavaScript:如何强制Image()不使用浏览器缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆