JSFiddle - React, Tailwind, and code Playground
by polarity
HTML
<canvas id="canvas" width="400" height="400"></canvas>
JavaScript
/**
2d spheretracing with several elementary shapes
A good visualization of the concept of raymarching
**/
function sketch(pjs) {
with(pjs) {
size(400, 400);
frameRate(60);
// max iterations
const MAX_ITERS = 70;
const shapes = {
// **centered** rect
rectangle: function(x, y, w, h) {
return {
x: x,
y: y,
w: w,
h: h,
findDistance: function(a, b) {
let x = abs(a - this.x);
y = abs(b - this.y);
let w = this.w / 2;
let h = this.h / 2;
let xMult = max(x, w) - w;
let yMult = max(y, h) - h;
return sqrt(xMult * xMult + yMult * yMult) + max(min(x, w) - w, min(y, h) - h);
},
draw: function() {
rect(this.x - this.w / 2, this.y - this.h / 2, this.w, this.h);
}
};
},
circle: function(x, y, r) {
return {
x: x,
y: y,
r: r,
findDistance: function(a, b) {
return dist(this.x, this.y, a, b) - this.r;
},
draw: function() {
ellipse(this.x, this.y, 2 * this.r, 2 * this.r);
}
};
},
line: function(x1, y1, x2, y2) {
return {
x1: x1,
x2: x2,
y1: y1,
y2: y2,
findDistance: function(a, b) {
return Math.abs((this.y2 - this.y1) * a - (this.x2 - this.x1) * b + this.x2 * this.y1 - this.y2 * this.x1) / dist(this.x1, this.y1, this.x2, this.y2);
},
draw: function(a, b) {
line(this.x1, this.y1, this.x2, this.y2);
}
};
}
};
// boundary lines and the shapes
let things = [shapes.rectangle(100, 200, 100, 100), shapes.circle(300, 300, 50), shapes.line(0, 0, width, 0), shapes.line(0, 0, 0, height), shapes.line(width, height, width, 0), shapes.line(width, height, 0, height)];
let raymarch =...