JSTURTLE

by John Doe

HTML

<!--<html>-->
    <!--<head><meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"/></head>-->
    
    <body>
        <canvas id="myCanvas" width="640" height="480" style="border:1px solid #000000;" />
        <script type="text/javascript">
            
        </script>
    </body>

<!--</html>-->

JavaScript

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, 150, 75);
var tp = 2 * Math.PI;

function Turtle() {
    var r2d = 180 / Math.PI;
    var d2r = 1 / r2d;
    this.pos = [c.width / 2, c.height / 2];
    this.dir = [1, 0];
    ctx.beginPath();
    ctx.moveTo(this.pos[0], this.pos[1]);
    this.setPos = function (pos) {
        this.pos = pos.slice();
        ctx.moveTo(this.pos[0], this.pos[1]);
        return this;
    };
    this.getPos = function () {
        return this.pos.slice();
    }
    this.getDir = function () {
        return this.dir.slice();
    };
    this.setDir = function () {
        if (arguments.length == 1 && !Array.isArray(arguments[0])) {
            this.dir = [1, 0];
            this.turn(arguments[0]);
        } else if (arguments.length == 1 && Array.isArray(arguments[0])) {
            this.setDir(arguments[0][0], arguments[0][1]);
        } else if (arguments.length == 2) {
            var l = Math.sqrt(arguments[0] * arguments[0] + arguments[1] * arguments[1]);
            this.dir[0] = arguments[0] / l;
            this.dir[1] = arguments[1] / l;
        }
        return this;
    }
    this.turn = function (alpha) { //turns right
        alpha *= d2r;
        var tempdir = this.dir[0] * Math.cos(alpha) - this.dir[1] * Math.sin(alpha);
        this.dir[1] = this.dir[0] * Math.sin(alpha) + this.dir[1] * Math.cos(alpha);
        this.dir[0] = tempdir;
        ctx.stroke();
        return this;
    };
    this.turnLeft = function () {
        this.turn(-90);
        return this;
    };
    this.turnRight = function () {
        this.turn(90);
        return this;
    };
    this.drawTo = function (target) {
        ctx.lineTo(target[0], target[1]);
        this.pos = target.slice();
        ctx.stroke();
        return this;
    };
    this.drawVec = function (vec) {
        this.drawTo([this.pos[0] + vec[0], this.pos[1] + vec[1]]);
        this.pos[0] += vec[0];
  ...