Introducing Dragonfly Cloud! Learn More

Question: How do you draw a rectangle in Love2D?

Answer

In Love2D, drawing a rectangle is accomplished through the love.graphics.rectangle function. Here's a basic example of how to use it:

function love.draw() -- Set the color for the rectangle (R, G, B, A) love.graphics.setColor(1, 0, 0, 1) -- Red color -- Draw a filled rectangle -- Parameters: mode, x, y, width, height love.graphics.rectangle('fill', 100, 100, 200, 150) -- Set a different color (optional) love.graphics.setColor(0, 1, 0, 1) -- Green color -- Draw an outline of a rectangle -- Parameters: mode, x, y, width, height love.graphics.rectangle('line', 400, 100, 200, 150) end

Here’s what each parameter of love.graphics.rectangle means:

  • The first parameter is the mode. It can be 'fill' to draw a filled rectangle, or 'line' to draw just the outline.
  • The second and third parameters are the x and y coordinates for the top-left corner of the rectangle.
  • The fourth and fifth parameters are the width and height of the rectangle.

Before drawing shapes, it's common to set the current drawing color using love.graphics.setColor(). This function takes four arguments defining the red, green, blue, and alpha values, with each value being between 0 and 1.

When you're done drawing shapes or at the start of a new frame, it might be necessary to reset the drawing color to white with full opacity:

love.graphics.setColor(1, 1, 1, 1)

This ensures that any textures or images drawn afterward will render with their original colors and full opacity.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Start building today 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.