JSFiddle - React, Tailwind, and code Playground
by Kyle Falconer
JavaScript
// based on http://www.reddit.com/r/javascript/comments/18suqe/i_got_bored_so_i_made_a_3d_cubey_thingy/
//First things first, place our canvas
var box = document.createElement("canvas");
box.height = 400;
box.width = 400;
document.body.appendChild(box);
var canvas = box.getContext("2d");
var fps = 0, framesC = 0;
var updateFn = window.requestAnimationFrame || // standards
window.mozRequestAnimationFrame || // Firefox
window.msRequestAnimationFrame || // IE 10 PP2+
window.oRequestAnimationFrame || // Opera/Presto
window.webkitRequestAnimationFrame || // Chrome/Webkit
function(f){ setInterval(f, 17);}; // 17ms used by Google
//Drawing functions to make life easier and not duplicate code
function drawCircle(coord, r) {
canvas.beginPath();
canvas.arc(coord[0], coord[1], r, 0, Math.PI * 2, true);
canvas.closePath();
canvas.fill();
}
function rotateX(array, amount) {
return [array[0]*Math.cos(amount)-array[2]*Math.sin(amount),
array[1],
array[0]*Math.sin(amount)+array[2]*Math.cos(amount)
];
}
//hold the points for my cube
var cubeVert = [
100, -100, -100,
-100, -100, -100,
-100, -100, 100,
100, -100, 100,
100, 100, -100,
-100, 100, -100,
-100, 100, 100,
100, 100, 100
];
var focal = 700;
//projects 3D to 2D
function to2D (coord) {
var scale=focal/(coord[2]+focal);
return [(coord[0]*scale)+200, (coord[1]*scale)+200];
}
//returns 3D coords at certain point in array
function next3 (array, start) {
return [array[3*start], array[3*start+1], array[3*start+2]];
}
//draws all of the things. No update yet
var count = 0;
var speed = 100;
var update = function() {
canvas.fillStyle="white";
canvas.beginPath();
canvas.rect(0, 0, 400, 400);
canvas.closePath();
canvas.fill();
canvas.fillStyle="black";
for(var i=0; i<8; i++) {
var coord = next3(cubeVert, i);
...