HTML5 Canvas在绘图上闪烁 [英] HTML5 Canvas blinking on drawing
问题描述
我开始使用等距游戏,当绘制地面的所有部分时,我的画布闪烁(不在IE中)。当我将fps设置为20或更低时,闪烁停止。我怎么解决这个问题?有什么想法吗?
I'm beginning with an isometric game, and my canvas is blinking(Not in IE) when draws all the parts of the ground. When I set fps to 20 or less, the blinking stops. How can I solve that? Any ideas?
var camerax = 300, cameray = 100;
var fps = 60;
function draw() {
clearCanvas();
drawGround();
}
function drawGround() {
var img = new Image();
img.onload = function() {
var width = img.width;
var height = img.height;
for (var x = 0; x < 3; x++) {
for (var y = 3; y >= 0; y--) {
mx = (x-y)*height + camerax;
my = (x+y)*height/2 + cameray;
ctx.drawImage(img, mx, my);
}
}
}
img.src = "ground.png";
}
var loop = setInterval(function() {
update();
draw();
}, 1000/fps);
推荐答案
现在你每帧重新加载图像除非 onload
回调在帧的16ms内触发,否则你将看到一个空白画布。
Right now you're reloading the image every frame and unless the onload
callback fires within the 16ms of the frame you're going to see a blank canvas.
你应该只需要调用新图像
, img.onload
序列,以预加载图像。然后 onload
回调将启动你的第一帧,并且绘制调用可以自由使用内存中的图像。
You should only need to call the new Image
, img.onload
sequence once, to preload your images. The onload
callback would then kick off your first frame, and the draw calls are free to use the image in memory.
类似于:
var camerax = 300, cameray = 100;
var fps = 60;
var img;
var loop;
function init() {
img = new Image();
img.onload = function() {
loop = setInterval(function() {
update();
draw();
}, 1000/fps);
};
img.src = "ground.png";
}
function draw() {
clearCanvas();
drawGround();
}
function drawGround() {
var width = img.width;
var height = img.height;
for (var x = 0; x < 3; x++) {
for (var y = 3; y >= 0; y--) {
mx = (x-y)*height + camerax;
my = (x+y)*height/2 + cameray;
ctx.drawImage(img, mx, my);
}
}
}
}
当然,一旦你等待多个图像预加载就会变得更复杂,因为只有在完成所有这些图像后才需要启动循环。
Of course, it gets more complex once you're waiting for multiple images to preload since you need to start the loop only once all of them are done.
这篇关于HTML5 Canvas在绘图上闪烁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!