As we get acquainted with drawing lines in the previous lesson and understand how screen coordinate system works, let's advance to drawing some basic shapes. Here we paint a green-filled rectangle:
graph.init()
graph.rect(50, 100, 50, 100, 'green')
the function graph.rect
takes 5
arguments:
X
and Y
values follow first - coordinates of the top-left cornerWidth
and Height
are following, they define the size of the rectangleColor
here is, it could be either human-readable word or browser color definition (we'll see this later)We can draw several overlapping rectangles:
graph.init()
graph.rect(50, 50, 150, 100, 'red')
graph.rect(70, 70, 150, 100, 'green')
graph.rect(90, 90, 150, 100, 'blue')
How to color lines
Lines from the previous lesson can be colored also, but for them color is set with separate function graph.color
- this makes sense since we often need to draw several lines of the same color at once:
graph.init()
graph.color('orange')
graph.line(50, graph.h/2, graph.w/2, 35)
graph.line(graph.w/2, 35, graph.w-50, graph.h/2)
graph.color('purple')
graph.line(50, graph.h/2, graph.w/2, graph.h-35)
graph.line(graph.w/2, graph.h-35, graph.w-50, graph.h/2)
This way the rhombus shape should be created: we set current color to orange
, draw two upper lines, then change
the color to purple
and draw two lower lines.
More subtle shades of colors
We mentioned the colors could be not only specified by their names - there are other ways. Most versatile is by
specifying exact red-green-blue components value of a color. One of the formats for this is a string with the
word rgb
and three numbers in parentheses, e.g.
graph.color('rgb(200, 50, 255)')
Here 200
is value for red, 50
for green and 255
for blue. All values should be in the range 0..255
.
It may be a bit confusing why rgb
which looks like typical function call is inside quotes, but it is a manner for
specifying color for browser, it is always a kind of textual string - so it is not a function really, rather some
magical web-style specification.
Interesting consequence is that we can generate such a color-definition strings in a loop, changing components gradually. For example, let us draw many small rectangles (2x2
pixels each), incrementing blue component from
right to left and incrementing red component from top to bottom:
graph.init()
for y = 0,255 do
for x = 0,255 do
color = 'rgb(' .. y .. ',0,' .. x .. ')'
graph.rect(x*2, y*2, 2, 2, color)
end
end