使用javascript从url中获取图像 [英] Fetching image from url with javascript
问题描述
我想尝试在不同网址的页面上显示图片。
I am trying to show an image on my page from a different url.
<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>
其他网站上的图片每1.5秒保存一次。
结果是我无法查看图像。
任何想法为什么?
谢谢!
The image on the other site is being saved every 1.5 seconds.
The result is that I cant view the image.
Any ideas why?
Thanks!
推荐答案
1。缓存问题
您的 MyPicture.png
返回缓存控制:max-age = 31536000 HTTP响应中的
。因此浏览器可能会在第二次从其缓存中获取图像。你需要添加像thie这样的查询字符串:
1. Cache issue
Your MyPicture.png
returns Cache-Control: max-age=31536000
in HTTP response. So browser may get image from its cache on second time. You need to add query string something like thie:
img.src = "http://yinoneliraz-001-site1.smarterasp.net/MyPicture.png?time=" + (new Date()).getTime();
2。提取周期太短。
我认为提取周期200毫秒太短。最好将 onload
事件处理程序绑定到图像对象。请参阅如何获取要显示的远程图像画布?。
2. Too short fetching period.
I think fetching period 200msec is too short. It's better to bind onload
event handler to the image object. See How to fetch a remote image to display in a canvas?.
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();
}
3。双缓冲
我认为你的脚本打算预先加载图片。因此最好进行双缓冲。
3. Double buffering
I think your script intend to pre-load image. So it's better to make a double buffering.
单缓冲版本: http://jsfiddle.net/tokkonoPapa/dSJmy/1/
Double Buffering版本: http://jsfiddle.net/tokkonoPapa/dSJmy/2/
Double Buffering version: http://jsfiddle.net/tokkonoPapa/dSJmy/2/
这篇关于使用javascript从url中获取图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!