# Sharing code for a filled polygon

Hello,

I needed some code for a filled polygon (my actual problem was a triangle)
So I made it and thought I would share.
Use the code in setup() and the returned image in draw(), because the generation is kind of slow.
For non retina screens the x and y loop can be 1 instead of 0.5

``````function setup()
myimage = filledpolygon()
end

function draw()
background(40, 40, 50)
sprite(myimage,300,400)
end

function filledpolygon()
px = {} py = {}      -- x and y coordinates polygon corners
xmax = 0 ymax = 0
----------------------------------------- define polygon --
fill(255, 0, 214, 255) noStroke()      -- color -----------
n = 4                                  -- no sides --------
px[1] = 0        py[1] = 0             -- corner ----------
px[2] = 100      py[2] = 200           -- corner ----------
px[3] = 300      py[3] = 50            -- corner ----------
px[4] = 150      py[4] = 80            -- corner ----------
-----------------------------------------------------------
for i = 1,n do if px[i] > xmax then xmax = px[i] end end
for i = 1,n do if py[i] > ymax then ymax = py[i] end end
img = image(xmax,ymax)
setContext(img)
for x = 0,xmax,0.5 do
for y = 0,ymax,0.5 do
j = n oddNodes = false
for i = 1,n do
test = false
if py[i] < y and py[j] >= y then test = true end
if py[j] < y and py[i] >= y then test = true end
if test == true then
if px[i]+(y-py[i])/(py[j]-py[i])*(px[j]-px[i]) < x then
if oddNodes == false then oddNodes = true else oddNodes = false end
end
end
j = i
end
if oddNodes == true then rect(x,y,1,1) end
end
end
setContext()
return img
end

``````

Hope it is usable

Re Peter

Refined a bit, so that the corner co-ordinates is passed to the function.
The fill was semi transparent before, so I have changed the size of the small rectangles that is drawn to the image.

here is the function

``````function drawpolygon(px,py,fr,fg,fb,fa)
n = 0 for i = 1,100 do if px[i] == nil then break else n = n+1 end end
xmax = 0 for i = 1,n do if px[i] > xmax then xmax = px[i] end end
ymax = 0 for i = 1,n do if py[i] > ymax then ymax = py[i] end end
fill(fr,fg,fb,fa) noStroke()
img = image(xmax,ymax) setContext(img)
for x = 0,xmax,0.5 do
for y = 0,ymax,0.5 do
j = n odd = false
for i = 1,n do
test = false
if py[i] < y and py[j] >= y then test = true end
if py[j] < y and py[i] >= y then test = true end
if test == true then
if px[i]+(y-py[i])/(py[j]-py[i])*(px[j]-px[i]) < x then
if odd == false then odd = true else odd = false end
end
end
j = i
end
if odd == true then rect(x,y,2,2) end
end
end
setContext()
return img
end
``````

and here a call example (remember in setup() only)

``````px = {0,100,300,150}
py = {0,200,50,80}
myimage = drawpolygon(px,py,255,0,214,255)
``````

Re Peter

@macflyerdk - Zoyt has a better solution

``````--p is a table of vec2 node positions, c is the colour
function DrawPoly(p,c)
local m=mesh()
m.vertices=triangulate(p)
m:setColors(c)
return m
end
``````