Drawing
- To draw more complex shapes:
- Combine primitives
- Draw back-to-front, layering the image
- Called “Painter’s Algorithm”
gc.translate(x, y) moves the origin of the canvas coordinate system. After calling it, all drawing is offset by (x, y).
gc.translate(100, 50);
gc.fillRect(0, 0, 50, 50); // This draws at (100, 50) now
gc.scale(sx, sy): scales the coordinate system. sx, sy scale horizontally and vertically
gc.scale(2, 2);
gc.fillRect(0, 0, 50, 50); // Actually draws a 100×100 square
- Displaylist:
- Keep an ordered display list of Drawable objects
- Add objects to array from back to front
- (Could also add “z-depth” field and sort when object added)
- To draw all objects:
- iterate through list and draw each one
- As a rule, don’t optimize redrawing everything every frame until you have to
- A cached drawable optimizes rendering by giving each drawable object its own off-screen canvas (image buffer) to draw into only when its properties change. Instead of redrawing the object from scratch every frame, the main canvas simply copies this pre-rendered buffer image, which is much faster. To ensure the buffer stays up to date, a “redraw” flag is triggered whenever the object’s state changes. This approach greatly improves performance, especially when dealing with many static or rarely changing objects.