Donut.js
Hire me now, and get a cool Donut in your website!
Canvas Implimentation of Donut
Lorem ipsum dolor sit amet consectetur adipisicing elit. Ut reiciendis est, totam debitis modi accusantium eos
laboriosam doloremque. Nulla corrupti suscipit quisquam beatae cupiditate voluptatem maiores fuga temporibus,
enim, esse voluptatum! Tempore ratione sunt iure?
Lorem ipsum dolor sit amet consectetur adipisicing elit. Ut reiciendis est, totam debitis modi accusantium eos
laboriosam doloremque. Nulla corrupti suscipit quisquam beatae cupiditate voluptatem maiores fuga temporibus,
enim, esse voluptatum! Tempore ratione sunt iure?
Lorem ipsum dolor sit amet consectetur adipisicing elit. Ut reiciendis est, totam debitis modi accusantium eos
laboriosam doloremque.
// * random code to make me seem smart 🤓
// This is a reimplementation according to donut.c's math derivation on [githubRepo]
const R1 = 1;
const R2 = 2;
const K1 = 150;
const K2 = 5;
const canvasframe = function () {
const ctx = canvastag.getContext("2d");
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
// precompute cosines and sines of A, B, theta, phi, same as before
const cA = Math.cos(A),
sA = Math.sin(A),
cB = Math.cos(B),
sB = Math.sin(B);
for (let j = 0; j < 6.28; j +=0.3) {
// j <=> theta
const ct = Math.cos(j),
st = Math.sin(j); // cosine theta, sine theta
for (i = 0; i < 6.28; i +=0.1) {
// i <=> phi
const sp = Math.sin(i),
cp = Math.cos(i); // cosine phi, sine phi
const ox = R2 + R1 * ct, // object x, y = (R2,0,0) + (R1 cos theta, R1 sin
theta, 0)
oy = R1 * st;
const x = ox * (cB * cp + sA * sB * sp) - oy * cA * sB; // final 3D x
coordinate
const y = ox * (sB * cp - sA * cB * sp) + oy * cA * cB; // final 3D y
// * size //
const ooz = 2 / (K2 + cA * ox * sp + sA * oy); // one over z
const xp = 300 + K1 * ooz * x;
// x' = screen space coordinate, translated and scaled to fit our 320x240 canvas element
const yp = 270 - K1 * ooz * y;
// y' (it's negative here because in our output, positive y goes down but in our 3D space, positive y goes up)
// luminance, scaled back to 0 to 1
const L =
0.7 *
(cp * ct * sB -
cA * ct * sp -
sA * st +
cB * (cA * st - ct * sA * sp));
if (L > 0) {
ctx.fillStyle = "rgba(255,255,255," + L + ")";
ctx.fillRect(xp, yp, 2, 2);
}
}
}
};