'canvas("2d").getImageData() slows down the animation loop [duplicate]
function gameCycle() {
draw_all();
if (!Tank1.destroyed){
rotation_Tank1();
movement_Tank1();
Shooting_Tank1();
}
if (!Tank2.destroyed){
rotation_Tank2();
movement_Tank2();
Shooting_Tank2();
}
c.strokeStyle = "#ffffff";
Draw_tank1();
Draw_tank2();
collision(Tank1);
collision(Tank2);
// console.log("Bullets_Tank1: " + Tank1.bullet_count);
for (var i = 0;i < bullets.length;i++){
// console.log(bullets[i].get_x());
if (bullets[i].bullet_end()){
bullets[i].get_tank().bullet_count--;
bullets.splice(i, 1);
c.clearRect(0, 0,canv.width, canv.height);
if (!Tank1.destroyed){
Draw_tank1();
}
if (!Tank2.destroyed){
Draw_tank2();
}
}
else{
bullets[i].update();
bullets[i].check_obstacle();
}
}
window.requestAnimationFrame(gameCycle);
//THIS FUNCTION CAUSES THE ANIMATION FRAME TO SLOW DOWN. THIS GETS THE PIXEL VALUE OF THE BULLET.
function getData(x, y){
const data = c.getImageData(x, y, 1, 1).data;
if (data[0] == 0 && data[1] == 0 && data[2] == 0 && data[3] == 255){
return false;
}
else{return true;}
}
//THIS IS THE FUNCTION IN THE BULLET CLASS AND THE ARRAY BULLETS CONTAINS ALL THE INSTANCES OF BULLET CLASS
check_obstacle(){
if (getData(this.x, this.y)){
console.log("Collision");
}
}
The above code runner fine without calling the getdata function. It does not causes the fucntion to slow down instantly however, it slows the fucntion when multiple instances of the bullet are made and stored in bullets (maximum 6 instances).
Solution 1:[1]
This may be the solution you are looking for:
A faster alternative to canvas.getImageData
If not this is some other information:
A lot of other programmers seem to have the exact same problem that you are having
as shown here: Issue 1001845: Performance regression in calling getImageData (HWA)
and here: Issue 81497: getImageData really slow in chrome
I am unsure of how essential the use of this function is to this project, but I suggest trying to find a workaround or trying to find a solution
here: Speed up Canvas's getImageData() and putImageData()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yipee Coder |
