我正在使用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