Drawing a grid of squares efficiently with OpenGL
in
Core Library Questions
•
3 months ago
I'm working on a sketch (targeted for fullscreen in Present mode) that draws a grid of random colored squares to the screen at a given scale. This happens every frame, and I'm using a PGraphics as an offscreen buffer.
The following code does exactly what I need and runs fine on my computer, but it eats up about 20% of my CPU. Since it's such a simple operation, I suspect there's probably a better way to do it I don't know about.
The following code does exactly what I need and runs fine on my computer, but it eats up about 20% of my CPU. Since it's such a simple operation, I suspect there's probably a better way to do it I don't know about.
- PGraphics canvas;
- final int scale = 5; // side length of squares
- final int xCenter = displayWidth / 2;
- final int yCenter = displayHeight / 2;
- void setup() {
- size(displayWidth, displayHeight, P2D);
- canvas = createGraphics(displayWidth, displayHeight, P2D);
- canvas.imageMode(CENTER);
- }
- void draw() {
- canvas.beginDraw();
- canvas.noStroke();
- for(int i = 0; i < displayWidth; i+=scale) {
- for(int j = 0; j < displayHeight; j+=scale) {
- canvas.fill(random(255), random(255), random(255));
- canvas.rect(i, j, scale, scale);
- }
- }
- canvas.endDraw();
- image(canvas, xCenter, yCenter);
- }
1