JSFiddle - React, Tailwind, and code Playground

by tomatofractal

HTML

<!doctype html>
<html>
  <head>
    <title>This is the title of the webpage!</title>
		<link rel="icon" href="data:;base64,=">
		<script type="module" src="src/rasterizer.js"></script>
  </head>
  <body>
		<div style="display:flex; justify-content: center; align-items:center; height:100vh">
			<canvas style="border: 1px solid  #eee " id="canvas" width="480" height="480"> 
			</canvas>	
		</div>
  </body>
</html>

JavaScript

const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");

const width = canvas.width;
const height = canvas.height;

const canvasBuffer = context.getImageData(0, 0, width, height);

const blit = () => {
  context.putImageData(canvasBuffer, 0, 0);
};

const canvasPixel = (x, y, r, g, b, a) => {
  x = Math.floor(x);
  y = Math.floor(y);
  const index = (x + y * width) * 4;
  canvasBuffer.data[index + 0] = r;
  canvasBuffer.data[index + 1] = g;
  canvasBuffer.data[index + 2] = b;
  canvasBuffer.data[index + 3] = a;
};

const putPixel = (x, y, color) => {
  let canvasX = width / 2 + x;
  let canvasY = height / 2 - y;

  canvasPixel(canvasX, canvasY, color.r, color.g, color.b, color.a);
};

const drawLine = (p0, p1, color) => {
  let dx = p1.x - p0.x;
  let dy = p1.y - p0.y;

  if (Math.abs(dx) > Math.abs(dy)) {
    if (p0.x > p1.x) {
      let copy = p1;
      p1 = p0;
      p0 = copy;
    }
    const a = dy / dx;
    let b = p0.y - a * p0.x;

    for (let x = p0.x; x < p1.x; x++) {
      console.log(color);
      if (color.r === 255) console.log("red");
      let y = a * x + b;
      putPixel(x, y, color);
    }
  } else {
    if (p0.y > p1.y) {
      let copy = p1;
      p1 = p0;
      p0 = copy;
    }

    const a = dx / dy;
    const b = p0.x - a * p0.y;

    for (let y = p0.y; y < p1.y; y++) {
      let x = a * y + b;
      putPixel(x, y, color);
      // x = x + a;
    }
  }
};

const lines = [
  {
    start: { x: 0, y: 0 },
    end: { x: 0, y: 100 },
    color: { r: 255, g: 0, b: 0, a: 255 },
  },
  {
    start: { x: 0, y: 25 },
    end: { x: -100, y: 100 },
    color: { r: 0, g: 200, b: 0, a: 255 },
  },
  {
    start: { x: -60, y: 30 },
    end: { x: -100, y: 120 },
    color: { r: 0, g: 0, b: 200, a: 255 },
  },
];

lines.forEach((line) => {
  drawLine(line.start, line.end, line.color);
});

blit();