Skip to content

Instantly share code, notes, and snippets.

@mik30s
Created May 8, 2019 02:53
Show Gist options
  • Save mik30s/ce2fc6aa345f373dfd3bc5927f587075 to your computer and use it in GitHub Desktop.
Save mik30s/ce2fc6aa345f373dfd3bc5927f587075 to your computer and use it in GitHub Desktop.
Simple mesh rendering with the bresenham algo
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<canvas id="canvas"></canvas>
<style>
body {
margin: 0px;
}
</style>
<script>
let canvas = document.getElementById("canvas")
let ctx = canvas.getContext("2d");
console.log("loaded canvas context", ctx);
ctx.fillStyle = "black";
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.fillRect(0, 0, canvas.width, canvas.height);
function resize() {
canvas.clientWidth = window.innerWidth;
canvas.clientHeight = window.innerHeight;
}
window.onresize = resize;
function line(start, end, color) {
let steep = false;
let x0 = start[0];
let x1 = end[0];
let y0 = start[1];
let y1 = end[1];
if (Math.abs(x0 - x1) < Math.abs(y0 - y1)) {
[x0, y0] = [y0, x0];
[x1, y1] = [y1, x1];
steep = true;
}
if (x0 > x1) {
[x0, x1] = [x1, x0];
[y0, y1] = [y1, y0];
}
let pixel = ctx.createImageData(1,1);
pixel.data[0] = color[0];
pixel.data[1] = color[1];
pixel.data[2] = color[2];
pixel.data[3] = color[3];
for (let x = x0; x <= x1; x++) {
let t = (x- x0) / (x1 - x0);
let y = y0 * (1 - t) + y1 * t;
if (steep) {
ctx.putImageData(pixel, y,x);
} else {
ctx.putImageData(pixel, x,y);
}
}
}
function load(filename, callback) {
let vertices = [];
let faces = [];
var rawFile = new XMLHttpRequest();
rawFile.open("GET", filename, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status === 0)
{
var allText = rawFile.responseText;
//alert(allText);
// get line
let lines = allText.split('\n')
for (let i = 0; i < lines.length; i++) {
let dataMarker = lines[i][0];
if (dataMarker === "v") {
// we have a vertex
let xyz = lines[i].split(' ').slice(1)
vertices.push(xyz.map((n) => parseFloat(n,10)));
} else if (dataMarker === "f") {
let face = lines[i].split(' ').slice(1);
face = face.map((f) => parseInt(f.split("/")[0]))
faces.push(face);
}
}
// draw mesh
callback(vertices, faces);
}
}
}
rawFile.send(null);
}
function drawMesh(filename, screenWidth, screenHeight) {
load(filename, (vertices, faces) => {
// console.log(vertices)
//console.log(faces);
for (let i = 0; i < faces.length; i++) {
let face = faces[i];
for (let j = 0; j < 3; j++) {
let first = vertices[face[j]];
let second = vertices[face[(j+1)%3]];
let x0 = (first[0]+1)*screenWidth/2;
let y0 = (first[1]+1)*screenHeight/2;
let x1 = (second[0]+1)*screenWidth/2;
let y1 = (second[1]+1)*screenHeight/2;
line([x0,y0],[x1,y1], [255,255,255,255]);
}
}
});
}
drawMesh("african_head.obj",canvas.width,canvas.height);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment