Published
Edited
Jan 21, 2020
2 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
canvas = {
const pixels = imageData.data;
const rgbColor = hexToRGB(hexColor); // parse hex to RGB

const cx = canvasWidth / 2, cy = canvasHeight / 2;
const radius2 = radius * radius;
const negLight = light.map(x => -x);
let i = 0;
for (let y = 0; y < canvasHeight; y++) {
for (let x = 0; x < canvasWidth; x++, i += 4) {
const dx = x - cx;
const dy = y - cy;
const d2 = dx*dx + dy*dy;
if (d2 <= radius2) {
const normal = normalize([
Math.sin(dx / radius * Math.PI/2),
Math.cos(dy / radius * Math.PI/2 + Math.PI/2),
Math.sqrt(radius2 - dx*dx - dy*dy) / radius
]);

// diffuse comes from light absorbing or bouncing off of the surface,
// so it's a function of the angle (dot product) between the light and the surface
const nDotL = dot(normal, negLight);
let diffuse = Math.max(0, nDotL) * diffuseStrength; // diffuse
diffuse += ambientStrength; // ambient light is background light that's always present

let specular = 0;
if (nDotL > 0) {
const lightReflect = reflect(light, normal); // reflect light direction off surface normal
const eye = [0, 0, radius * 20];
const eyeToSurface = normalize(sub(eye, normal.map(x => x * radius))); // eye looking at surface
// specular comes from light bouncing off the surface and into the eye,
// so it's a function of the angle (dot product) between the two
specular = Math.pow(Math.max(0, dot(eyeToSurface, lightReflect)), shiny);
specular *= specularStrength;
specular *= 255; // to byte range
}

pixels[i + 0] = rgbColor[0] * diffuse + specular;
pixels[i + 1] = rgbColor[1] * diffuse + specular;
pixels[i + 2] = rgbColor[2] * diffuse + specular;
pixels[i + 3] = 255;
}
else {
pixels[i + 0] = 0;
pixels[i + 1] = 0;
pixels[i + 2] = 0;
pixels[i + 3] = 255;
}
}
}
ctx.putImageData(imageData, 0, 0);
return ctx.canvas;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
lengthSq = (v) => v.map(x => x * x).reduce((a, b) => a + b);
Insert cell
Insert cell
Insert cell
Insert cell
mult = (a, b) => a.map((x, i) => x * b[i]);
Insert cell
sub = (a, b) => a.map((x, i) => x - b[i]);
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