JSFiddle - React, Tailwind, and code Playground

by alexvestin

JavaScript

const canvas = document.createElement("canvas")
canvas.width = 512;
canvas.height = 512;
canvas.style.backgroundColor = "black"
document.body.appendChild(canvas)

const ctx = canvas.getContext("2d");


const INSIDE = 0; // 0000
const LEFT = 1;   // 0001
const RIGHT = 2;  // 0010
const BOTTOM = 4; // 0100
const TOP = 8;    // 1000
const TILE_SIZE = 32;


const compute_out_code = (x, y, xmin, xmax, ymin, ymax)  => {
	var code = INSIDE;

	if (x < xmin) {
        code = code | LEFT;
    } else if (x > xmax) {
        code = code | RIGHT;
    }     
		
	if (y < ymax) {
        code = code | TOP;
    } else if (y > ymin) {
        code = code | BOTTOM;
    }     
		
	return code;
}



const clip_line = (line, top_left) =>  {
    let {x0,y0,x1,y1} = line;
        
    let xmin = top_left.x;
    let ymin = top_left.y + TILE_SIZE;
    let xmax = top_left.x + TILE_SIZE;
    let ymax = top_left.y;

    var outcode0 = compute_out_code(x0, y0, xmin, xmax, ymin, ymax);
    var outcode1 = compute_out_code(x1, y1, xmin, xmax, ymin, ymax);

    var accept = false;
    while(true) {
        if (!(outcode0 | outcode1)) {
            accept = true;
            break;
        } else if((outcode0 & outcode1)) {
            break;
        }

        var x
        var y
        let outcode_out =  outcode1 > outcode0 ? outcode1 : outcode0;
        let dy = y1 - y0;
        let dx = x1 - x0;
        if ((outcode_out & TOP)) {           // point is above the clip window
            x = x0 + dx * (ymax - y0) / dy;
            y = ymax;
        } else if ((outcode_out & BOTTOM)) { // point is below the clip window
            x = x0 + dx * (ymin - y0) / dy;
            y = ymin;
        } else if ((outcode_out & RIGHT)) {  // point is to the right of clip window
            y = y0 + dy * (xmax - x0) / dx;
            x = xmax;
        } else if ((outcode_out & LEFT)) {   // point is to the left of clip window
            y = y0 + dy * (xmin - x0) / dx;
            x = xmin;
        }

      ...