I wrote a renderer of sorts that can create Signed Distance Fields in Javascript / Canvas
https://jsfiddle.net/MisterSirCode/zrbx8493/273/
It works well, but the SDFs it renders, while accurate, are rough and pixelated
(Im calculating each pixel manually and applying the color data based on the X Y position / distance and then editing the image data of the canvas)
This is less than what I want to achieve. I want the rendered SDFs to have an anti-aliased appearance, but I’ve never made an algorithm to achieve it, and I’ve found little online that could help me.
What I want to know is, how can I correctly alias the corners and edges of my SDFs to give them a smoother appearance from far away.
This is the main function I draw my SDFs onto the image data with: (The full source code is in the above link)
draw() {
let image = this.ctx.createImageData(this.image);
let ivec = new Vector(image.width, image.height);
for (var y = 0; y < image.height; ++y) {
for (var x = 0; x < image.width; ++x) {
let sphereOne = SDF.sphere(new Vector(ivec.x / 2, ivec.y / 2), 25)(new Vector(x, y, 1));
let sphereTwo = SDF.sphere(new Vector(ivec.x / 4, ivec.y / 4), 15)(new Vector(x, y, 1));
let dist = SDF.smoothAdd(sphereOne, sphereTwo, 35);
let pos = (y * image.width + x) * 4;
if (dist < 0) {
image.data[pos++] = x / image.width * 255;
image.data[pos++] = y / image.height * 255;
image.data[pos++] = (image.width - x) / image.width * 255;
image.data[pos] = 255;
} else {
let bc = this.scene.backColor;
image.data[pos++] = bc[0] * 255;
image.data[pos++] = bc[1] * 255;
image.data[pos++] = bc[2] * 255;
image.data[pos] = bc[3] * 255;
}
}
}
this.ctx.putImageData(image, 0, 0);
}