JSFiddle - React, Tailwind, and code Playground
by alexvestin
JavaScript
const scale = 32;
const canvas = document.createElement("canvas")
canvas.width = 2048;
canvas.height = 2048;
document.body.appendChild(canvas)
const ctx = canvas.getContext("2d");
const TILE_SIZE = 16;
const NEGATION = 15;
let numTileLines = canvas.width / TILE_SIZE;
ctx.fillStyle = "white";
ctx.fillRect(0, 0, 2048, 2048);
ctx.strokeStyle = "black";
ctx.lineWidth = 4 / scale;
ctx.beginPath()
ctx.scale(scale, scale);
const setPixelAA = (x, y, opacity) => {
ctx.fillStyle = "blue";
ctx.globalAlpha = 1.;
ctx.fillRect(Math.floor(x), Math.floor(y), 1, 1)
ctx.globalAlpha = 1.0;
//console.log(x, y, opacity)
}
const touches = (tlx, tly, x0, y0, x1, y1) => {
const left = x0 < tlx && x1 < tlx;
const right = x0 > tlx && x1 > tlx;
const top = y0 < tly && y1 < tly;
return true;
}
const get_tile = (v) => {
const n = Number(v < 0) * NEGATION;
return ((v - n) / TILE_SIZE) * TILE_SIZE;
}
const setUpRay = (l, dx, dy, dtdx, dtdy) => {
const r = { row_t0: 0, col_t0: 0, row_t1: 0, col_t1: 0, line: l, tile: 0, x: 0, y: 0 };
r.x = Math.floor(l.x0);
r.y = Math.floor(l.y0);
const tl_x = get_tile(r.x);
const tl_y = get_tile(r.y);
if (Math.abs(dy > 0.00001)) {
const next_y = l.y1 > l.y0 ? tl_y + TILE_SIZE : tl_y;
r.row_t1 = Math.min((dtdy * (next_y - l.y0)) / TILE_SIZE, 1.0)
}
if (Math.abs(dx > 0.00001)) {
const next_x = l.x1 > l.x0 ? tl_x + TILE_SIZE : tl_x;
r.row_t1 = Math.min((dtdy * (next_x - l.x0)) / TILE_SIZE, 1.0)
}
return r;
}
const stepRays = (l1, l2) => {
const dx = l1.x1 - l1.x0;
const dy = l1.y1 - l1.y0;
const dtdx = TILE_SIZE / dx;
const dtdy = TILE_SIZE / dy;
const x_step = Math.abs(dtdx);
const y_step = Math.abs(dtdx);
const r0 = setUpRay(l1, dx, dy, dtdx, dtdy);
const r1 = setUpRay(l2, dx, dy, dtdx, dtdy);
while (true) {
const r0_t1 = Math.min(r0.row_t1, r0.col_t1);
const r1_t1 = Math.min(r1.row_t1, r1.col_t1);
const r = r0_t1 < r1_t1 ? r0 :...