00 How it works
01 Objects - Constructor
02 Objects - Constructor (drawing)
03 Objects - Constructor (timing)
04 Objects - Prototype (sequential declaration)
05 Objects - Prototype (declaring all at once)
Code goes here:
var _things = 0; var _cross = 16 / 2; function Thing(angle) { // Variables declared in constructor are private to the constuctor. var thing_num = ++_things; // Variables accessed trhough 'this' keyword are public and visible everywhere. this.x = 0; this.y = 0; this.alpha = (angle && angle!=NaN) ? angle / 180.0*Math.PI : 0; // Class methods follow this.step = function(distance) { this.x += distance * Math.cos(this.alpha); this.y += distance * Math.sin(this.alpha); return this; }; this.turn_degrees = function(degrees) { this.alpha += degrees / 180.0*Math.PI; return this; }; this.update = function(canvas, domelement) { console.log("Thing #" + thing_num + " is at:", it01.x, 'x', it01.y, "and looks at", this.aplha * 180.0/Math.PI, "degrees"); return this; }; this.draw = function(ctx2d) { ctx2d.setTransform(1, 0, 0, 1, 0, 0); ctx2d.translate(ctx.canvas.width / 2, ctx.canvas.height / 2); ctx2d.beginPath(); ctx2d.moveTo(this.x - _cross, this.y); ctx2d.lineTo(this.x + _cross, this.y); ctx2d.moveTo(this.x, this.y - _cross); ctx2d.lineTo(this.x, this.y + _cross); ctx2d.stroke(); return this; }; this.mark = function(elem) { elem.style.position = 'absolute'; elem.style.top = this.y + 'px'; elem.style.left = this.x + 'px'; return this; }; } var it01 = new Thing(); var dom_marker = document.getElementById('dom_marker'); var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var steps = [30, 30, 15]; var turns = [null, 10, 80]; it01.update().draw(ctx).mark(dom_marker) .step(steps[0]).update().draw(ctx).mark(dom_marker) .turn_degrees(turns[1]).step(steps[1]).update().draw(ctx).mark(dom_marker) .turn_degrees(turns[2]).step(steps[2]).update().draw(ctx).mark(dom_marker);
Ctrl+Enter to Run this code
Logs show up here:
Here, we draw on a canvas
And finally, DOM + CSS
x