我正在画布的背景上绘制图像。此图像每秒刷新一次,但画布需要每0.5秒更频繁地重绘一次。我似乎遇到的问题是Safari在更新画布时闪烁,因为它似乎丢失了bgImg变量中的图像数据。 Firefox按预期工作,不会出现闪烁。
有没有人知道如何避免这种情况?我错过了一些非常明显的东西吗?
要测试此代码,只需将下面的整个代码粘贴到html文件中,然后使用浏览器加载。它应该做的是:
以下是代码:
<html>
<head>
<script type="text/javascript">
var bgImg = new Image();
var firstload = false;
var cv;
var ctx;
var updateBackground = function() {
bgImg.onload = function() {
firstload = true;
console.log("image loaded. Dimensions are " + bgImg.width + "x" + bgImg.height);
}
bgImg.src = "http://mopra-ops.atnf.csiro.au/TOAD/temp.php?" + Math.random() * 10000000;
setTimeout(updateBackground, 1000);
}
var initGraphics = function() {
cv = document.getElementById("canvas");
ctx = cv.getContext("2d");
cv.width = cv.clientWidth;
cv.height = cv.clientHeight;
cv.top = 0;
cv.left = 0;
}
var drawStuff = function() {
console.log("Draw called. firstload = " + firstload );
ctx.clearRect(0, 0, cv.width, cv.height);
if ( firstload == true) {
console.log("Drawing image. Dimensions are " + bgImg.width + "x" + bgImg.height);
try {
ctx.drawImage(bgImg, 0, 0);
} catch(err) {
console.log('Oops! Something bad happened: ' + err);
}
}
setTimeout(drawStuff, 500);
}
window.onload = function() {
initGraphics();
setTimeout(updateBackground, 1000);
setTimeout(drawStuff, 500);
}
</script>
<style>
body {
background: #000000;
font-family: Verdana, Arial, sans-serif;
font-size: 10px;
color: #cccccc;
}
.maindisplay {
position:absolute;
top: 3%;
left: 1%;
height: 96%;
width: 96%;
text-align: left;
border: 1px solid #cccccc;
}
</style>
</head>
<body>
<div id="myspan" style="width: 50%">
<canvas id="canvas" class="maindisplay"></canvas>
</div>
</body>
</html>
答案 0 :(得分:0)
您的问题是您在加载时正在绘制bgImg
。 Webkit在加载新图像时不会缓存旧图像数据;一旦设置了新的.src
,它就会清除图像。
您可以使用两张图片来修复此问题,使用最后一次加载的图片进行绘图,同时加载下一张图片。
我在网上举了一个例子:http://jsfiddle.net/3XW8q/2/
简化Stack Overflow后代:
var imgs=[new Image,new Image], validImage, imgIndex=0;
function initGraphics() {
// Whenever an image loads, record it as the latest-valid image for drawing
imgs[0].onload = imgs[1].onload = function(){ validImage = this; };
}
function loadNewImage(){
// When it's time to load a new image, pick one you didn't last use
var nextImage = imgs[imgIndex++ % imgs.length];
nextImage.src = "..."+Math.random();
setTimeout(loadNewImage, 2000);
}
function updateCanvas(){
if (validImage){ // Wait for the first valid image to load
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.drawImage(validImage, 0, 0);
}
setTimeout(updateCanvas, 500);
}