A grid is simply rounding all coordinate inputs to the nearest grid position.
So if your grid size was 1 pixel by 1 pixel, you would round all numbers to the nearest whole number.
If your grid size is 32, you would divide by 32, round, then multiply by 32 again. gridx=round(x/32)*32.