Published
Edited
Mar 2, 2019
2 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
rain = {
function renderRain(amount = 500, options = {}) {

options = defaultRainOptions(options);




let w = 960,
h = 500;




const canvas = DOM.canvas(w,h);

let context = d3.select(canvas).node().getContext('2d');


let rainDrops = d3.range(amount).map(function () {
let zIndex = getRandomArbitrary(0, 10);
return {
x: getRandomArbitrary(-10, w),
y: getRandomArbitrary(-100, -600),
z: zIndex,
d: map(zIndex, 0, 10, 3, 10),
length: map(zIndex, 0, 10, options.minLength, options.maxLength),
}
})



let timer = d3.timer(function () {
context.clearRect(0, 0,w,h);

for (let i = 0, length = rainDrops.length; i < length; i++) {
let x = rainDrops[i].x
let oldx = rainDrops[i].x;
let y = rainDrops[i].y
let dropLength = rainDrops[i].length;

x += wind

y += rainDrops[i].d;
if (y > h) {
y = getRandomArbitrary(-100, -600);
x = getRandomArbitrary(-100, w+100);
}

rainDrops[i].y = y;

context.beginPath();
context.moveTo(rainDrops[i].x,y);
context.lineTo(x,y+dropLength);
context.stroke();
context.closePath();

if (x > w) {
x = getRandomArbitrary(-100, w+100);
} else if (x < 0) {
x = getRandomArbitrary(-100, w+100);
}

rainDrops[i].x = x;
}

})
invalidation.then(() => timer.stop());
return canvas;
}



function defaultRainOptions(options) {
const MINLENGTH = 5,
MAXLENGTH = 20;

if (!("minLength" in options)) {
options.minLength = MINLENGTH;
}

if (!("maxLength" in options)) {
options.maxLength = MAXLENGTH;
}




return options;
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}

function map (num, in_min, in_max, out_min, out_max){
return (num - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
function defaultRainOptions(options) {
const MINLENGTH = 5,
MAXLENGTH = 20;

if (!("minLength" in options)) {
options.minLength = MINLENGTH;
}

if (!("maxLength" in options)) {
options.maxLength = MAXLENGTH;
}




return options;
}



return renderRain(numberDrops);
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more