自动刷新html画布图像不起作用

时间:2016-12-29 07:17:03

标签: javascript html html5 canvas

对于我的网站,我需要从不断更新的服务器重绘图像。我找到了解决方案但尝试了但它仍然没有自动刷新。我还尝试在我的图像(local0.jpg)中添加一个虚拟字符串,以便浏览器不使用缓存图像但没有成功。我做错了什么?

<html>
<head>
<meta charset="utf-8">
</head>
<body>
 <canvas id="canvas" width="400" height="400"> </canvas>
 <script>
 var imageObj=new Image();
 imageObj.src="local0.jpg?dummy=8484744"
 imageObj.onload=function()
 {
   var c = document.getElementById("canvas");
   var ctx = c.getContext("2d");
   ctx.drawImage(imageObj,0, 0,canvas.width,canvas.height);
   setTimeout(timedRefresh,1000);
 }
 function timedRefresh() 
 {
   imageObj.src = "local0.jpg?dummy=8484749"
 }
 </script>
 </body>
 </html>

2 个答案:

答案 0 :(得分:0)

您的函数timedRefresh将随机值添加到图像

 function timedRefresh() 
 {
   imageObj.src = "local0.jpg?dummy=" + Math.floor((Math.random() * 10000) + 1);
 }

答案 1 :(得分:0)

尝试以下代码

var imageObj = new Image();
imageObj.onload = function() {
    drawOnCanvas();
    setTimeout(timedRefresh, 1000);
  }
  // set src AFTER assigning load
imageObj.src = "local0.jpg?dummy=" + Math.random();

function timedRefresh() {
  imageObj.src = "local0.jpg?dummy=" + Math.random();
  //drawOnCanvas(); //flicker was due this line as it try to draw image load so i commented it... now it should work... 
}

function drawOnCanvas() {
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.drawImage(imageObj, 0, 0, canvas.width, canvas.height);
}