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