pool matho
pool matho

Reputation: 39

Canvas game framerate drop

Good evening, first i'm not sure i should post this here, since i have litteraly no idea what's wrong here (only clue is it happened after i moved all my variables at the top of my code while trying to "clean up" a little).

but here is the problem: i've created a canvas game and after moving my variables (i think) i started getting major framedrops. Game weighs less than 20Ko, images are super tiny and simple, i have a for loop in the update loop but it never seemed to be a problem (it's not infinite) so in short i do not know what's wrong here

here is a bit of code since links to code "must be accompanied by code" (dont know what's up with that)

for (var i = 0; i<boxes.length; i++){
    ctx.rect(boxes[i].x, boxes[i].y, boxes[i].width, boxes[i].height);
    var col = coli(player,boxes[i])
};

i've tried different things, like disabling functions (anim and colision), friction and gravity but nothing seems to have any effect, and i dont know that much about the dom except how to look at my own variables so i havent found anything with firebug.

Really hope someone has an idea

Upvotes: 0

Views: 123

Answers (1)

Blindman67
Blindman67

Reputation: 54026

You need to add ctx.beginPath() before using ctx.rect, moveTo, lineTo, arc, and any function you need to use ctx.stroke() or ctx.fill() to see.

beginPath tell the canvas 2D context that you wish to start a new shape. If you do not do this you end up adding more and more shapes each update.

From your fiddle

function update() {
  ctx.clearRect(0, 0, width, height);
  ctx.fillStyle = pat;
  //===============================================================
  ctx.beginPath()  // <=== this will fix your problem. It removes all the
  //                       previous rects
  //===============================================================
  for (var i = 0; i < boxes.length; i++) {
    ctx.rect(boxes[i].x, boxes[i].y, boxes[i].width, boxes[i].height);
    // or use ctx.fillRect(...
    var col = coli(player, boxes[i])
  };
  ctx.fill();    

Upvotes: 1

Related Questions