Skip to content

Instantly share code, notes, and snippets.

@gregtatum
Created January 5, 2017 04:17
Show Gist options
  • Save gregtatum/c8144c4da987a1c2e818cd716b9848a0 to your computer and use it in GitHub Desktop.
Save gregtatum/c8144c4da987a1c2e818cd716b9848a0 to your computer and use it in GitHub Desktop.
const random = require('@tatumcreative/random')("3")
const simplex = new (require('simplex-noise'))(random)
const clamp = require('clamp')
const TAU = 6.283185307179586
const WIDTH = 400
const HEIGHT = 100
const COUNT = 300
const STEP = 4
const START_THETA = TAU * 0.75
const THETA_RANGE = TAU * 0.10
const THETA_NOISE_PERIOD = 0.04
const THETA_NOISE_AMPLITUDE = 0.4
const NOISE_OFFSET = 0.008
const LINE_WIDTH = 3
const ROUNDING_AMOUNT = 1.5
module.exports = function createGrass () {
const canvas = document.createElement('canvas')
document.body.appendChild(canvas)
canvas.width = WIDTH
canvas.height = HEIGHT
canvas.style.position = "absolute"
const ctx = canvas.getContext('2d')
ctx.lineCap = "round";
const roots = Array.from({length: COUNT}, () => {
const x = random(0, 1)
return {
left: x * WIDTH,
top: random(0, HEIGHT * 0.5) + Math.abs(x - 0.5) * HEIGHT * ROUNDING_AMOUNT,
shapeOffset: random(0, WIDTH * NOISE_OFFSET)
}
})
roots.forEach(({left, top, shapeOffset}) => {
let x = left
let y = HEIGHT
let theta = TAU * 0.75
ctx.beginPath()
ctx.moveTo(x, y)
ctx.strokeColor =
ctx.lineWidth = LINE_WIDTH * (16 / (16 + top))
while (y > top) {
const thetaNoise = theta + THETA_NOISE_AMPLITUDE * simplex.noise2D(
THETA_NOISE_PERIOD * x + shapeOffset,
THETA_NOISE_PERIOD * y
)
theta = clamp(thetaNoise, START_THETA - THETA_RANGE, START_THETA + THETA_RANGE)
x += Math.cos(theta) * STEP
y += Math.sin(theta) * STEP
ctx.lineTo(x, y)
}
ctx.stroke()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment