0

I have a draw function that's drawing a colored rectangle over the whole canvas by calling the fillRect() function of its context, then calls a method within an object that was handed the same context by its constructor, that's drawing a rectangle at this object's x and y coordinates. The draw function is looped.

I would expect to see the following:

  1. fillRect() overwrites the whole canvas
  2. rect() (called as an object's method) draws a rectangle at the specified location

  3. fillRect() overwrites the whole canvas, including the drawn rectangle

  4. rect() (called as an object's method) draws a rectangle at the specified location

  5. ...

Sadly the fillRect() never actually draws "above" the rectangles drawn at the object position from within those objects' methods.

The code to reproduce this unexpected behaviour is about 60 lines long, so I'll link a jsfiddle instead of including it in here. By clicking the canvas you can create new objects to be drawn. They wander down the screen (leaving a trace, that's the problem) and are removed when out of screen (yet their trace will forever be visible). The only time where their traces can't be seen is when the draw method from within the objects is not called (no objects on screen), however as soon as a new object is created, ALL previous traces re-appear.

I am using something similar to a c-style linked list (I know I shouldn't) to store the objects that are supposed to be drawn.

jsfiddle linked again, for convenience.

wexa
  • 23
  • 5
  • 2
    Insert `cc.beginPath();` right before `cc.fillRect(0, 0, c.width, c.height);` (also see: https://stackoverflow.com/a/4677639/5734311) – Chris G Dec 26 '17 at 00:23
  • I get it. `fillRect()` wasn't the problem, but the `rect()` method keeps on adding to the path. I can't believe that I've been accidentally circumventing this for at least a year in easily a dozen projects using canvas - simply because I called `beginPath()` elsewhere. I just didn't know that `rect()` was part of the path. Thanks a lot. – wexa Dec 26 '17 at 10:46

0 Answers0