Mar*_*son 10 javascript caching image
如果我在浏览器中手动加载nextimg URL,则每次重新加载时都会显示新图片.但是这段代码在每次迭代时显示相同的图像draw()
.
如何强制myimg不被缓存?
<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>
Run Code Online (Sandbox Code Playgroud)
Dan*_*Dan 24
最简单的方法是将不断变化的查询字符串放到最后:
var url = 'http://.../?' + escape(new Date())
Run Code Online (Sandbox Code Playgroud)
有些人喜欢用Math.random()
它来代替escape(new Date())
.但正确的方法可能是更改Web服务器发送的标头以禁止缓存.
你无法阻止它在Javascript中完全缓存图像.但是,您可以使用图像的src /地址来强制它重新缓存:
[Image].src = 'image.png?' + (new Date()).getTime();
Run Code Online (Sandbox Code Playgroud)
您可以使用任何Ajax缓存解决方案并在此处应用它.
这实际上听起来像是浏览器中的一个错误 - 你可以在http://bugs.webkit.org上提交,如果它在Safari中,或者在https://bugzilla.mozilla.org/上用于Firefox.为什么我说潜在的浏览器错误?因为浏览器意识到它不应该在重新加载时缓存,但是当您以编程方式请求它时,它确实会为您提供图像的缓存副本.
那说你确定你真的在画任何东西吗?Canvas.drawImage API不会等待加载图像,并且当您尝试使用图像时,如果图像尚未完全加载,则指定不绘制.
更好的做法是:
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'
Run Code Online (Sandbox Code Playgroud)
(您也可以将draw
参数作为参数传递给setTimeout而不是使用字符串,这将保存重新分析并反复编译相同的字符串.)