Skip to main content

Medium shaders · colour · trigonometry

Plasma

Add four sine waves, push the sum through three more, and the canvas starts to look molten.

Write plasma(x, y, size). It is called for every pixel of a size by size canvas, x running right and y running down from 0 at the top left. Return a colour [r, g, b] with each channel from 0 to 255.

First add four waves and average them: v = (Math.sin(x / 8) + Math.sin(y / 8) + Math.sin((x + y) / 16) + Math.sin(d / 8)) / 4 where d is the distance from (x, y) to the centre (size / 2, size / 2). v lands between -1 and 1.

Then turn v into colour with three sine waves a third of a turn apart: r = 128 + 127 * Math.sin(Math.PI * v) g = 128 + 127 * Math.sin(Math.PI * v + 2 * Math.PI / 3) b = 128 + 127 * Math.sin(Math.PI * v + 4 * Math.PI / 3) Return [r, g, b] without rounding.

Example: at the top left, x = y = 0 and d is about 45.25, so v is about -0.1465 and plasma(0, 0, 64) is close to [71.6, 254.7, 57.7]. Answers are checked to within 0.000001.

Tests you can see

  • plasma(0, 0, 64)[71.57515695663076,254.7463132323461,57.678529811023225]
  • plasma(32, 32, 64)[3.8533688686727032,166.89012156534054,213.2565095659868]

More tests are hidden. The server runs them all before a time counts.

Run your code and this canvas paints itself.

javascriptplasma()

Tab indents · Cmd/Ctrl+Enter runs