Cra*_*aig 15 html refresh canvas image
我正在使用html在浏览器上显示一个图像(来自文件)...我有另一个程序,它一直拍摄我的屏幕截图并将其存储为图像文件"image.jpeg".我使用setTimeout定期在浏览器上显示此图像.但是图像在浏览器上没有变化..
这是我的代码...我使用了一个Image对象,以便每次javascript函数运行时都会加载一个新图像,但这似乎不起作用...
<html>
<head>
<script type="text/JavaScript">
var x=0, y=0;
var canvas, context, img;
function timedRefresh(timeoutPeriod)
{
canvas = document.getElementById("x");
context = canvas.getContext("2d");
img = new Image();
img.src = "image.jpeg";
context.drawImage(img, x, y);
x+=20; y+=20;
//img.destroy();
setTimeout("timedRefresh(1000)",timeoutPeriod);
}
</script>
<title>JavaScript Refresh Example</title>
</head>
<body onload="JavaScript:timedRefresh(1000);">
<canvas id="x" width="600" height="600" />
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
Yan*_*hon 14
首先,当您设置src
图像对象的属性时,图像尚未加载,您需要onload
在图像被触发时刷新画布(当图像加载完成时).
其次,浏览器尝试使用缓存的图像image.jpeg
.为避免这种情况,请在图像URI中添加一个伪造的参数.
例如 :
var timeoutPeriod = 1000;
var imageURI = 'image.jpeg';
var x=0, y=0;
var img = new Image();
img.onload = function() {
var canvas = document.getElementById("x");
var context = canvas.getContext("2d");
context.drawImage(img, x, y);
x+=20; y+=20;
setTimeout(timedRefresh,timeoutPeriod);
};
function timedRefresh() {
// just change src attribute, will always trigger the onload callback
img.src = imageURI + '?d=' + Date.now();
}
Run Code Online (Sandbox Code Playgroud)
然后它应该工作.
这是一个完整的工作示例.只需配置url
和refeshInterval
.它使用Yannick的缓存预防,并且不会img
像Piotr建议的那样在每次重新加载时重新创建对象.
<html>
<head>
<script type="text/JavaScript">
var url = "cam1.php"; //url to load image from
var refreshInterval = 1000; //in ms
var drawDate = true; //draw date string
var img;
function init() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
img = new Image();
img.onload = function() {
canvas.setAttribute("width", img.width)
canvas.setAttribute("height", img.height)
context.drawImage(this, 0, 0);
if(drawDate) {
var now = new Date();
var text = now.toLocaleDateString() + " " + now.toLocaleTimeString();
var maxWidth = 100;
var x = img.width-10-maxWidth;
var y = img.height-10;
context.strokeStyle = 'black';
context.lineWidth = 2;
context.strokeText(text, x, y, maxWidth);
context.fillStyle = 'white';
context.fillText(text, x, y, maxWidth);
}
};
refresh();
}
function refresh()
{
img.src = url + "?t=" + new Date().getTime();
setTimeout("refresh()",refreshInterval);
}
</script>
<title>JavaScript Refresh Example</title>
</head>
<body onload="JavaScript:init();">
<canvas id="canvas"/>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)