Created
February 1, 2018 22:28
-
-
Save sxywu/47ae1976604ccdb5ea79705934662d03 to your computer and use it in GitHub Desktop.
Watercolor attempt #1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _ from 'lodash'; | |
import * as d3 from 'd3'; | |
import p5 from 'p5'; | |
let root; | |
let canvas; | |
let ctx; | |
const width = 900; | |
const height = 900; | |
function calculatePolygon(radius, x, y) { | |
const points = _.times(10, i => { | |
return [ | |
_.round(radius * Math.cos(i * Math.PI / 5) + x, 2), | |
_.round(radius * Math.sin(i * Math.PI / 5) + y, 2), | |
] | |
}); | |
points.push(points[0]); // put first one back in | |
return points; | |
} | |
function recursePoints(point1, point2, countdown) { | |
const [x1, y1] = point1; | |
const [x2, y2] = point2; | |
const [mx, my] = [_.round((x1 + x2) / 2, 2), _.round((y1 + y2) / 2, 2)]; | |
const midpoint = [ | |
p5.prototype.randomGaussian(mx, _.random(5, 10)), | |
p5.prototype.randomGaussian(my, _.random(5, 10)) | |
]; | |
if (!countdown) return [midpoint]; // if countdown is down to 0 | |
return _.flatten([ | |
recursePoints(point1, midpoint, countdown - 1), | |
[midpoint], | |
recursePoints(midpoint, point2, countdown - 1) | |
]); | |
} | |
function loopPoints(points) { | |
let finalPoints = []; | |
let prevPoint = null; | |
_.each(points, (point, i) => { | |
if (i === 0) { | |
prevPoint = point; | |
return; | |
} | |
finalPoints = _.union(finalPoints, | |
[prevPoint], recursePoints(prevPoint, point, 2), [point]); | |
prevPoint = point; | |
}); | |
return finalPoints; | |
} | |
function draw(points, fill) { | |
ctx.fillStyle = fill; | |
ctx.beginPath(); | |
_.each(points, (point, i) => { | |
const [x, y] = point; | |
if (i === 0) { | |
ctx.moveTo(x, y); | |
return; | |
} | |
ctx.lineTo(x, y); | |
}); | |
ctx.fill(); | |
} | |
export default (node) => { | |
root = d3.select(node); | |
canvas = root.append('canvas') | |
.attr('width', width).attr('height', height); | |
ctx = canvas.node().getContext('2d'); | |
let points1 = calculatePolygon(200, width / 2 - _.random(200), height / 2); | |
points1 = loopPoints(points1); | |
let points2 = calculatePolygon(200, width / 2, height / 2 - _.random(200)); | |
points2 = loopPoints(points2); | |
_.times(40, i => { | |
const which = Math.floor(i / 5) % 2; | |
console.log(i, which) | |
const layer = loopPoints(which ? points1 : points2); | |
draw(layer, which ? 'rgba(255, 0, 0, 0.04)' : 'rgba(0, 0, 255, 0.04)'); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment