Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <canvas id="canvas" width="800" height="600">
              
            
!

CSS

              
                body {background:black}

canvas {border:1px solid darkgray}
              
            
!

JS

              
                type Vect2d = { x: number; y: number };
type Vect3d = { x: number; y: number; x: number };
type RGBA = { r: number; g: number; b: number; a: number };

const BLACK: RGBA = {r:0,g:0,b:0,a:255}
const RED: RGBA = {r:255,g:0,b:0,a:255}
const GREEN: RGBA = {r:0,g:255,b:0,a:255}
const BLUE: RGBA = {r:0,g:0,b:255,a:255}
const YELLOW: RGBA = {r:255,g:255,b:0,a:255}
const PURPLE: RGBA = {r:255,g:0,b:255,a:255}
const TEAL: RGBA = {r:0,g:255,b:255,a:255}

const FOV = 90

const cvs = document.getElementById("canvas");
const { width, height } = cvs;
const ctx = cvs.getContext("2d");
const z0 = (width/2)/Math.tan((FOV/2)*Math.PI/180)

class URLTexture {
	private imageData
	private width: number
	private height: number
	
	constructor(url) {
		const img = new Image()
		img.onload = () => {
			ctx.drawImage(img, 0, 0);
    	this.imageData = ctx.getImageData(0, 0, img.width, img.height).data;
			alert(this.imageData)
		}
		img.src = url
		this.width = img.width
		this.height = img.height
	}
	
	public getValue({x,y}: Vect2d): RGBA {
		if (x >= this.width) {
			x = this.width - 1
		}
		
		if (y >= this.height) {
			y = this.height - 1
		}
		
		return {
			r: this.imageData[(y * 4 * this.height) + (x * 4)],
			g: this.imageData[(y * 4 * this.height) + (x * 4) + 1],
			b: this.imageData[(y * 4 * this.height) + (x * 4) + 2],
			a: this.imageData[(y * 4 * this.height) + (x * 4) + 3]
		}
	}
}

class Triangle {
	private vertices: Vect3d[3]
  private worldCoords: Vect3d[3]
	private drawPoints: Vect3d[3]
	public averageZ: number
	public normalZ: number
	
	constructor(vertices: Vect3d[3], color: RGBA) {
		this.vertices = vertices
		this.color = color
		this.translate = {x:0,y:0,z:0}
		this.rotation = {x:0,y:0,z:0}
	}
	
	public calculateWorldCoords(position,rotation) {
		this.worldCoords = this.vertices
		
		this.worldCoords = this.worldCoords.map(vertex => rotate(vertex,rotation))
		
		this.worldCoords=this.worldCoords.map(vertex => translate(vertex,position))
		
		this.averageZ = (this.worldCoords[0].z + this.worldCoords[1].z + this.worldCoords[2].z) / 3
	}
	
	public calculateDrawPoints() {
		this.drawPoints=this.worldCoords.map(vertex => applyPerspective(vertex))
		
		this.drawPoints=this.drawPoints.map(vertex => centerScreen(vertex))
		
		this.normalZ = (this.drawPoints[1].x - this.drawPoints[0].x) * (this.drawPoints[2].y - this.drawPoints[0].y) - (this.drawPoints[1].y - this.drawPoints[0].y) * (this.drawPoints[2].x - this.drawPoints[0].x)
	}
	
	public draw(screenBuffer) {
		if (!this.drawPoints.length) return
		let aux
		
		if (this.drawPoints[0].y > this.drawPoints[1].y) {
			aux = this.drawPoints[0]
			this.drawPoints[0] = this.drawPoints[1]
			this.drawPoints[1] = aux
		}
		
		if (this.drawPoints[0].y > this.drawPoints[2].y) {
			aux = this.drawPoints[0]
			this.drawPoints[0] = this.drawPoints[2]
			this.drawPoints[2] = aux
		}
		
		if (this.drawPoints[1].y > this.drawPoints[2].y) {
			aux = this.drawPoints[1]
			this.drawPoints[1] = this.drawPoints[2]
			this.drawPoints[2] = aux
		}
		
		if (this.drawPoints[0].y < this.drawPoints[1].y) {
			const slope1 = (this.drawPoints[1].x - this.drawPoints[0].x) / (this.drawPoints[1].y - this.drawPoints[0].y)
			const slope2 = (this.drawPoints[2].x - this.drawPoints[0].x) / (this.drawPoints[2].y - this.drawPoints[0].y)
			for (let i = 0; i <= this.drawPoints[1].y - this.drawPoints[0].y; i++) {
				let x1 = this.drawPoints[0].x + i * slope1
				let x2 = this.drawPoints[0].x + i * slope2
				let y = this.drawPoints[0].y + i
				
				if (x1 > x2) {
					let aux = x1
					x1 = x2
					x2 = aux
				}
				
				for (let j = x1; j <= x2; j++) {
					screenBuffer.drawPixel({x:j,y},this.color)
				}
			}
		}
		
		if (this.drawPoints[1].y < this.drawPoints[2].y) {
			const slope1 = (this.drawPoints[2].x - this.drawPoints[1].x) / (this.drawPoints[2].y - this.drawPoints[1].y)
			const slope2 = (this.drawPoints[2].x - this.drawPoints[0].x) / (this.drawPoints[2].y - this.drawPoints[0].y)
			const sx = this.drawPoints[2].x - (this.drawPoints[2].y - this.drawPoints[1].y) * slope2
			
			for (let i = 0; i <= this.drawPoints[2].y - this.drawPoints[1].y; i++) {
				let x1 = this.drawPoints[1].x + i * slope1
				let x2 = sx + i * slope2
				let y = this.drawPoints[1].y + i
				
				if (x1 > x2) {
					let aux = x1
					x1 = x2
					x2 = aux
				}
				
				for (let j = x1; j <= x2; j++) {
					screenBuffer.drawPixel({x:j,y},this.color)
				}
			}
		}
	}
}

class Mesh {
	constructor(screenBuffer, vertices, triangles, translate, rotation) {
		this.screenBuffer = screenBuffer;
		this.triangles = triangles;
		this.translate = translate || {x:0,y:0,z:0}
		this.rotation = rotation||{x:0,y:0,z:0}
	}

	public draw() {
		this.triangles.forEach(tri => tri.rotation = this.rotation)
		this.triangles.forEach(tri => tri.translate = this.translate)
		this.triangles.forEach(triangle => triangle.draw(this.screenBuffer))
	}
}

class ScreenBuffer {
	constructor(ctx) {
		this.ctx = ctx;
		this.buffer = ctx.createImageData(width, height);
		this.pixels = this.buffer.data;
		this.numPixels = this.buffer.width * this.buffer.height;
	}

	public drawPixel(coords: Vect2d, color: RGBA) {
		const i = (this.buffer.width * Math.ceil(coords.y) + Math.ceil(coords.x)) * 4;
		this.pixels[i] = color.r;
		this.pixels[i + 1] = color.g;
		this.pixels[i + 2] = color.b;
		this.pixels[i + 3] = color.a;
	}

	public drawBuffer() {
		this.ctx.putImageData(this.buffer, 0, 0);
	}
}

function render(time) {
	// const crateTexture = new URLTexture("https://i.pinimg.com/originals/8e/33/fa/8e33fa90c71e445c9ce287acc0eea64e.jpg")
	// console.log(crateTexture.getValue({x:1,y:1}))
	
	const screenBuffer = new ScreenBuffer(ctx);
	const cubeVerts = [
		{ x: -50, y: -50, z: -50 },
		{ x: -50, y: 50, z: -50 },
		{ x: 50, y: 50, z: -50 },
		{ x: 50, y: -50, z: -50 },
		{ x: -50, y: -50, z: 50 },
		{ x: -50, y: 50, z: 50 },
		{ x: 50, y: 50, z: 50 },
		{ x: 50, y: -50, z: 50 },
	]
	
	const cubeTris = [
		// left
		new Triangle([cubeVerts[0],cubeVerts[1],cubeVerts[3]], YELLOW),
		new Triangle([cubeVerts[1],cubeVerts[2],cubeVerts[3]], YELLOW),
		// right
		new Triangle([cubeVerts[7],cubeVerts[5],cubeVerts[4]], RED),
		new Triangle([cubeVerts[7],cubeVerts[6],cubeVerts[5]], RED),
		// top
		new Triangle([cubeVerts[4],cubeVerts[0],cubeVerts[7]], GREEN),
		new Triangle([cubeVerts[0],cubeVerts[3],cubeVerts[7]], GREEN),
		// bottom
		new Triangle([cubeVerts[1],cubeVerts[6],cubeVerts[2]], PURPLE),
		new Triangle([cubeVerts[1],cubeVerts[5],cubeVerts[6]], PURPLE),
		// back
		new Triangle([cubeVerts[4],cubeVerts[1],cubeVerts[0]], BLUE),
		new Triangle([cubeVerts[4],cubeVerts[5],cubeVerts[1]], BLUE),
		// front
		new Triangle([cubeVerts[3],cubeVerts[2],cubeVerts[7]], TEAL),
		new Triangle([cubeVerts[7],cubeVerts[2],cubeVerts[6]], TEAL),
	]
	
	const cube = new Mesh(screenBuffer, cubeVerts, cubeTris);
	cube.rotation.y += 0.001 * time
	cube.rotation.x += 0.001 * time
	cube.rotation.z += 0.001 * time
	
	let triangles: Triangle[] = []
	
	cube.triangles.forEach(tri => {
		tri.calculateWorldCoords(cube.translate,cube.rotation)
		triangles.push(tri)
	})
	
	triangles.sort((a,b) => a.averageZ > b.averageZ?-1:1)
	triangles.forEach(tri => {
		tri.calculateDrawPoints()
		if (tri.normalZ < 0) {
		tri.draw(screenBuffer)
		}
	})

	screenBuffer.drawBuffer();
	requestAnimationFrame(render);
}
requestAnimationFrame(render);

function translate(original: Vect3d, translation: Vect3d): Vect3d {
	let transformedVector: Vect3d = {x:0,y:0,z:0}
	transformedVector.x = original.x + translation.x
	transformedVector.y = original.y + translation.y
	transformedVector.z = original.z + translation.z
	return transformedVector
} 

function rotate(original: Vect3d, rotation: Vect3d): Vect3d {
	let transformedVector: Vect3d = {x:0,y:0,z:0}
	transformedVector.x = original.x * (Math.cos(rotation.z) * Math.cos(rotation.y)) + 
				 original.y * (Math.cos(rotation.z) * Math.sin(rotation.y) * Math.sin(rotation.x) - Math.sin(rotation.z) * Math.cos(rotation.x)) +
				 original.z * (Math.cos(rotation.z) * Math.sin(rotation.y) * Math.cos(rotation.x) + Math.sin(rotation.z) * Math.sin(rotation.x))
	transformedVector.y = original.x * (Math.sin(rotation.z) * Math.cos(rotation.y)) +
				 original.y * (Math.sin(rotation.z) * Math.sin(rotation.y) * Math.sin(rotation.x) + Math.cos(rotation.z) * Math.cos(rotation.x)) +
				 original.z * (Math.sin(rotation.z) * Math.sin(rotation.y) * Math.cos(rotation.x) - Math.cos(rotation.z) * Math.sin(rotation.x))
	transformedVector.z = original.x * (- Math.sin(rotation.y)) +
				 original.y * (Math.cos(rotation.y) * Math.sin(rotation.x)) +
				 original.z * (Math.cos(rotation.y) * Math.cos(rotation.x))
	return transformedVector
} 

function applyPerspective({x,y,z}: Vect3d): Vect3d {
	let transformedVector: Vect3d = {x:0,y:0,z:0}
	transformedVector.x = x*z0/(z0+z)
	transformedVector.y = y*z0/(z0+z)
	transformedVector.z = z
	return transformedVector
}

function centerScreen(vector: Vect3d) {
	let transformedVector = {x:0,y:0,z:0}
	transformedVector.x = vector.x + width / 2
	transformedVector.y = vector.y + height / 2
	transformedVector.z = vector.z
	return 	transformedVector
}
              
            
!
999px

Console