Here is some code that you can use in Processing, which allows you to draw very smooth looking dithered gradients, either within the main display or inside PGraphics objects. Because they are dithered, they do not suffer from the “banding” effect that is created when strict integer rounding is used to interpolate colors. The dithering is optional and can be turned off with a boolean argument.

This code is only intended for use in Processing, and should only be used if speed is not essential! They can be used for creating art when high quality output is important, or could also be used in animation applications by drawing to PGraphics objects once at the beginning, which are stored and redrawn to the display later as needed.

Some JavaScript demos are below, but these are only for illustrating the gradients. Click on the screencaps below to see the demos: In the first, a radial gradient is drawn, dithered on top, not dithered on the bottom. You may not even notice the difference, depending on your monitor. Non-dithered gradients only look stepped when certain colors are used under the right conditions. In the second demo, colorful balls are drawn on a gradient background. The balls are created with radial gradients.

Look below for notes on how to use the code.

## How to use

Using the gradients is simple. They are defined similar to the way gradients are defined in JavaScript for the HTML5 canvas.

• To create a linear gradient with start point (x0,y0) and end point (x1,y1):
LinearGradient grad = new LinearGradient(x0,x1,y0,y1);
grad.addColorStop(ratio, color);

the ratio should be between 0 and 1, representing how far from beginning to end points this color will be reached.

• Filling a rectangle with this gradient – there are two versions:
• To fill a rectangle in the main sketch display with the gradient:
grad.fillRect(rectX, rectY, rectW, rectH, dither);
• To fill part of a PGraphics object pg with the gradient:
grad.fillRect(pg, rectX, rectY, rectW, rectH, dither);
• rectX, rectY, rectW, rectH define the rectangle,
• boolean dither argument sets whether to use dithering.

RadialGradient grad = new RadialGradient(x0, y0, rad0, x1, y1, rad1);