Tôi đang cố gắng tạo hoạt ảnh trong canvas. Lần đầu tiên nó hoạt động tốt nhưng khi một phần tử mới được thêm vào thông qua setTimeout, tất cả tốc độ của phần tử đều tăng lên. Bất cứ ai có thể cho tôi biết lý do tại sao tốc độ này đang tăng lên. Fiddle LinkHoạt ảnh canvas Html5 không hoạt động bình thường
var canvas = $("#canvas")[0],
context = canvas.getContext("2d"),
bloons = {},
bloonIndex = 0;
var c_wdh = 360,
c_hgt = 540;
function createBloon(x, y) {
this.x = x;
this.y = y;
this.vx = 1,
this.vy = 3;
bloonIndex++;
bloons[bloonIndex] = this;
this.id = bloonIndex;
}
createBloon.prototype.drawImage = function() {
this.y -= this.vy;
context.fillStyle = "#FF0000";
context.fillRect(this.x, this.y, 50, 50);
if(this.y <= -120){
delete bloons[this.id];
}
};
var nob = 0;
var i = 1;
var rendorBloon = setInterval(function(){
bloons[i] = new createBloon(Math.random() * c_wdh, c_hgt);
var animate = setInterval(function() {
context.clearRect(0, 0, c_wdh, c_hgt);
for (var i in bloons){
bloons[i].drawImage();
}
}, 30);
i++;
nob++;
if(nob >= 10){
clearInterval(rendorBloon);
}
}, 1000);
bạn đang gọi setInterval bên trong một setInterval, ý tưởng tồi ... Ngoài ra, đối với hoạt ảnh, sử dụng ['requestAnimationFrame()'] (https://developer.mozilla.org/en/docs/Web/API/window. requestAnimationFrame), setInterval thực sự không phải là phương thức thích hợp nếu bạn phải xử lý mọi thứ dựa trên thời gian. – Kaiido
Bạn cần gọi đến setInterval thứ hai bên ngoài phần đầu tiên https://jsfiddle.net/v5eoeybe/5/ – jcubic
@jcubic nhờ làm việc ngay bây giờ. –