4

What determines the origin of context.fillRect on an HTML5 canvas when using 2d...

 2 years ago
source link: https://www.codesd.com/item/what-determines-the-origin-of-context-fillrect-on-an-html5-canvas-when-using-2d-context.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

What determines the origin of context.fillRect on an HTML5 canvas when using 2d context?

advertisements

I am using the easelJS library with multiple bitmapSequence objects on my canvas. I may be asking the wrong question, because I don't understand how this works. I will try to explain my situation as clearly as I can.

I am placing multiple bitmapSequence objects (sprite animation sequences) on the canvas and moving them within the global tick() function, by setting the x and y properties. Once I set their x and y properties, I call stage.update(), which re-renders the canvas and all of the bitmapSequence objects with their new locations.

After the stage.update() call, but still within the tick() function, I assign the variable ctx to canvas.getContext('2d'). Then I call ctx.fillRect(0, 0, 8, 8). In this case the 0,0 (x,y) arguments for fillRect ALWAYS represents the origin point for the very last bitmapSequence object of which I modified the x and y attributes of prior to the stage.update() call.

This means if I draw a rectangle at 0,0 it will be show at the origin of the very last bitmapSequence object I used, and follow the bitmapSequence when I move it).

If I try to get a 2d context, and draw a rectangle prior to the stage.update() it does not show up on the canvas.

Ideally I would like to be able to draw rectangles relative to the origin of any bitmapSequence object I wish. Please help me understand what I am misunderstanding.


Maybe you are looking for translate() function? The behaviour of your program corresponds to behaviour of that function. So, if you want to reset the relative drawing, use ctx.translate(-x_of_last_bitmapSequence, -y_of_last_bitmapSequence).

Alternatively you can change the "starting point" of relative drawing:

ctx.save();
ctx.translate(x, y);

ctx.strokeRect(0, 0, 30, 30) // strokes a square at coords [x, y]

ctx.restore(); // restores the original state (relative coords are at [0, 0])


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK