我正在使用HTML5 Canvas和JavaScript创建这个简单的动画,我遇到了闪烁对象的问题。 我试图在互联网上找到解决方案之前,我问过这个问题,所有我发现基本上是:html canvas动画闪烁
- 避免加载新的形象,对象在每个新帧
- 使用
requestAnimationFrame()
我想我已经完成了这一切,闪烁仍在发生。 (蓝色矩形(障碍物)在我的情况
的作品是减少像素的方法,负责移动对象,这里的数唯一的解决办法:
obstacle.prototype.moveObstacle = function(){
this.x -=3
}
但动画太慢。 有周围没有任何办法
的jsfiddle:https://jsfiddle.net/wojmjaq6/
代码:
var cnv = document.getElementById("gameField");
var ctx = cnv.getContext("2d");
var speedY = 1
var obst1 = new obstacle(cnv.width + 50);
var myBird = new bird(100, 1);
function bird(x, y) {
this.x = x;
this.y = y;
this.gravity = 0.3
this.gravitySpeed = 0
}
bird.prototype.drawbird = function() {
ctx.fillStyle = "red"
ctx.fillRect(this.x, this.y, 20, 20);
}
bird.prototype.animate = function() {
this.gravitySpeed += this.gravity
this.y += speedY + this.gravitySpeed
}
function obstacle(x) {
this.x = x;
this.y = 0;
this.obstLen = Math.floor(Math.random() * 400)
}
obstacle.prototype.drawobstacle = function() {
ctx.fillStyle = "blue";
ctx.fillRect(this.x, this.y, 15, this.obstLen)
ctx.fillRect(this.x, cnv.height, 15, -(cnv.height - this.obstLen - 100))
}
obstacle.prototype.moveObstacle = function() {
this.x -= 3
}
function myFun() {
ctx.clearRect(0, 0, cnv.width, cnv.height);
myBird.animate();
myBird.drawbird();
obst1.moveObstacle();
obst1.drawobstacle();
if (obst1.x < 0) {
obst1 = new obstacle(cnv.width + 50);
}
window.requestAnimationFrame(myFun)
};
function test() {
if (myBird.gravity > 0) {
myBird.gravity = -1
} else {
myBird.gravity = 0.3
}
}
document.getElementById("gameField").onmousedown = test
document.getElementById("gameField").onmouseup = test
window.requestAnimationFrame(myFun)
我没有看到任何闪烁。 MacBook Air上的Safari和Chrome(2014年初)。 –
同样在这里,看起来不错 – Eric
它可能只是一个“弱”电脑的问题?因为我已经在Chrome,Firefox和IE上测试过它,并且它们都在闪烁。 – Pawel