Skip to content

Instantly share code, notes, and snippets.

@jmcd
Created June 1, 2018 15:20
Show Gist options
  • Save jmcd/292f5b8d4409d14563d69d895123fc68 to your computer and use it in GitHub Desktop.
Save jmcd/292f5b8d4409d14563d69d895123fc68 to your computer and use it in GitHub Desktop.
cubes
<html>
<body>
<canvas id="canvas" width="400" height="400" />
</body>
<script src="build/app.js"></script>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var scaleFactor = 20;
ctx.scale(scaleFactor, scaleFactor);
ctx.translate(0, 3);
Iso.cube(ctx, 1, 1, Iso.Color.blue);
ctx.translate(0, -1);
Iso.cube(ctx, 1, 1, Iso.Color.green);
ctx.translate(0, -1);
Iso.cube(ctx, 1, 1, Iso.Color.red);
ctx.translate(0, -1);
ctx.scale(1 / scaleFactor, 1 / scaleFactor);
</script>
</html>
namespace Iso {
function lface(ctx: CanvasRenderingContext2D, width: number, height: number) {
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(width, width / 2);
ctx.lineTo(width, height + width / 2);
ctx.lineTo(0, height);
ctx.closePath();
ctx.fill();
}
export function rface(ctx: CanvasRenderingContext2D, width: number, height: number) {
ctx.scale(-1, 1);
lface(ctx, width, height);
ctx.scale(-1, 1);
}
function lid(ctx: CanvasRenderingContext2D, width: number, height: number) {
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(width, width / 2);
ctx.lineTo(width * 2, 0);
ctx.lineTo(width, -width / 2);
ctx.closePath();
ctx.fill();
}
export function cube(ctx: CanvasRenderingContext2D, faceWidth: number, faceHeight: number, color: Color) {
let old = ctx.fillStyle;
ctx.fillStyle = color.scaledBy(0.9).toString();
lface(ctx, faceWidth, faceHeight);
ctx.translate(faceWidth * 2, 0);
ctx.fillStyle = color.scaledBy(0.8).toString();
rface(ctx, faceWidth, faceHeight);
ctx.translate(-faceWidth * 2, 0);
ctx.fillStyle = color.toString();
lid(ctx, faceWidth, faceHeight);
ctx.fillStyle = old;
}
export class Color {
static red = new Color(255, 0, 0);
static green = new Color(0, 255, 0);
static blue = new Color(0, 0, 255);
constructor(public r: number, public g: number, public b: number) {
this.r = Math.min(255, r);
this.g = Math.min(255, g);
this.b = Math.min(255, b);
}
toString(): string {
function hex(n: number): string {
var s = n.toString(16);
while (s.length < 2) s = "0" + s;
return s;
}
let result = "#" + hex(this.r) + hex(this.g) + hex(this.b);
console.log(result);
return result;
}
scaledBy(scale: number): Color {
return new Color(Math.round(this.r * scale), Math.round(this.g * scale), Math.round(this.b * scale));
}
}
}
@jmcd
Copy link
Author

jmcd commented Jun 4, 2018

screen shot 2018-06-01 at 16 21 47

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment