Skip to content

Commit 0a68131

Browse files
committed
better random color hue (not backward compatible)
1 parent e7c3709 commit 0a68131

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

pattern.go

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,9 +239,45 @@ func (g *generator) setOpacity(opacity float64) {
239239
g.opacity = opacity
240240
}
241241

242+
type basecolor struct {
243+
middle float64
244+
delta float64
245+
}
246+
247+
var colors = [...]basecolor{
248+
{0, 15}, // red
249+
{30, 15}, // orange
250+
{60, 15}, // yellow
251+
{120, 45}, // green
252+
{180, 15}, // cyan
253+
{225, 30}, // blue
254+
{270, 15}, // purple
255+
{315, 30}, // magenta
256+
}
257+
258+
// randomHue generate a random intéger in [0,360]
259+
// First it peaks one of the base colors,
260+
// then it adds a random deviation in [-delta, delta].
261+
// This is necessary to avoid 'green' to be 3 times more probable
262+
// than 'red', for example.
263+
264+
func (g *generator) randomHue() float64 {
265+
n := len(colors)
266+
if n <= 0 {
267+
return 0
268+
}
269+
i := g.rand.Intn(n)
270+
c := colors[i]
271+
h := c.middle + g.rd(c.delta)
272+
if h < 0 {
273+
h += 360
274+
}
275+
return h
276+
}
277+
242278
// randomColor generate a random background color.
243279
func (g *generator) randomColor() {
244-
randCol := colorful.Hsl(360*g.rand.Float64(), 0.3+0.1*g.rand.Float64(), 0.3+0.1*g.rand.Float64())
280+
randCol := colorful.Hsl(g.randomHue(), 0.3+0.1*g.rand.Float64(), 0.3+0.1*g.rand.Float64())
245281
g.setColor(randCol)
246282
}
247283

0 commit comments

Comments
 (0)