Yin*_*raz 1 html javascript image
我试图在我的页面上显示来自不同网址的图像。
<body>
<div id="container">
<br />
<canvas width="500px" height="375px" id="canvas">
</canvas>
<img src="http://yinoneliraz-001-site1.smarterasp.net/MyPicture.png" />
</div>
<script>
var img = new Image;
img.src = "http://yinoneliraz-001-site1.smarterasp.net/MyPicture.png";
var timer = setInterval(function () { MyTimer() }, 200);
function MyTimer() {
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0,500,675);
img = new Image;
img.src = "http://yinoneliraz-001-site1.smarterasp.net/MyPicture.png";
}
</script>
Run Code Online (Sandbox Code Playgroud)
另一个站点上的图像每 1.5 秒保存一次。
结果就是看不到图片。
有什么想法吗?
谢谢!
小智 5
您在 HTTP 响应中的MyPicture.png返回Cache-Control: max-age=31536000。因此浏览器可能会在第二次从缓存中获取图像。您需要添加类似 thie 的查询字符串:
img.src = "http://yinoneliraz-001-site1.smarterasp.net/MyPicture.png?time=" + (new Date()).getTime();
Run Code Online (Sandbox Code Playgroud)
我认为 200 毫秒的获取周期太短了。最好将onload事件处理程序绑定到图像对象。请参阅如何获取远程图像以在画布中显示?。
function copyCanvas(img) {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
}
function loadImage() {
var img = new Image();
img.onload = function () {
copyCanvas(img);
};
img.src = "http://yinoneliraz-001-site1.smarterasp.net/MyPicture.png?time=" + (new Date()).getTime();
}
Run Code Online (Sandbox Code Playgroud)
我认为你的脚本打算预加载图像。所以最好做双缓冲。
单缓冲版本:http://jsfiddle.net/tokkonoPapa/dSJmy/1/
双缓冲版本:http://jsfiddle.net/tokkonoPapa/dSJmy/2/