Created
December 9, 2011 12:52
-
-
Save knsmr/1451414 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| $(function(){ | |
| var canvas = $("#dragon")[0], | |
| ctx = canvas.getContext("2d"); | |
| $.extend(ctx, { | |
| strokeStyle: "rgb(255, 127, 0)", | |
| lineWidth: 1 | |
| }); | |
| var Turtle = function (x, y, vector) { | |
| this.x = x; | |
| this.y = y; | |
| ctx.moveTo(x, y); | |
| this.step = 20; | |
| this.vector = vector; | |
| }; | |
| $.extend(Turtle.prototype, { | |
| moveForward : function() { | |
| this.x = this.x + this.vector[0]; | |
| this.y = this.y + this.vector[1]; | |
| ctx.lineTo(this.x, this.y); | |
| ctx.stroke(); | |
| }, | |
| turnRight : function() { | |
| this.vector = [-this.vector[1], this.vector[0]]; | |
| }, | |
| turnLeft : function() { | |
| this.vector = [this.vector[1], -this.vector[0]]; | |
| } | |
| }); | |
| $('#button').on('click', function() {draw()}); | |
| function draw () { | |
| var order = $('#order').val(); | |
| var command = generateDragon(order); | |
| canvas.width = canvas.width; // clear the canvas | |
| ctx.translate(canvas.width / 2, canvas.height / 2); | |
| for (var i = 0; i < 4; i++) { | |
| drawSequence(command, canvas.width / (order * 30)); | |
| ctx.rotate(Math.PI * (90 / 180)); | |
| } | |
| } | |
| function drawSequence(command, f) { | |
| var ary = command.split(''); | |
| var t = new Turtle(0, 0, [5, 0]); | |
| ctx.beginPath(); | |
| while (ary.length > 0) { | |
| switch(ary.shift()) { | |
| case 'F': | |
| t.moveForward(); | |
| break; | |
| case '+': | |
| t.turnRight(); | |
| break; | |
| case '-': | |
| t.turnLeft(); | |
| break; | |
| } | |
| } | |
| } | |
| function generateDragon(order) { | |
| var command = "F"; | |
| for (var i = 1; i < order; i++) { | |
| // Dragon curve generation rule | |
| command = command.replace(/F/g, "F+F-F") | |
| } | |
| console.log(command); | |
| return command; | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment